DOM Based XSS and Adding HTML Elements


So as a rule of thumb I once learned that adding or removing HTML with JavaScript/JQuery (.html(),.append(), etc) leaves yourself wide open for DOM Based XSS Attacks. It is now my understanding that this is not 100% true. Supposedly there is a correct and safe way to add/remove HTML with JavaScript. I am hoping to learn some on what this “correct way” may be.

So as an example lets say I have an input filed that allows a user to append an item to a list. In this case the input would also be added to an array to be sent in future requests. Additionally this list would have a button to remove said item from that list. In an insecure environment we might do something like the following (negating array):

var list = $  ("#my_list");  $  ("#add_btn").on("click", function(){     let input = $  ("#input_field").val();     list.append(         '<li>'+input+' <button>Remove</button></li>'     ); });   $  ("#my_list").on("click", "button", function(){     $  (this).closest("li").remove(); }); 

How might one do the same but without the threat of XSS?