I have a div that is filled by JS created DOM elements,
I want the div to be cleared upon the JS function repeating, however I have heard that using document.getElementById('elName').innerHTML = "";
is not a good idea,
What is a valid alternative to doing this to clear the div's contents?
To clear the contents of a div element, set the element's textContent property to an empty string, e.g. div. textContent = '' . Setting textContent on the element removes all of its children and replaces them with a single text node of the provided value.
replaceChildren() is a convenient alternative to innerHTML and append() append() appends nodes to the parent node. The contents that were inside the node before the append() invocation remain preserved. What if I want to replace all the contents of the parent node?
The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies. You can read the MDN documentation on innerHTML .
The correct answer is that in certain situations you should use innerHTML, and in other situations you should use appendChild. Here's when to use innerHTML or appendChild: Use innerHTML when you're setting text inside of an HTML tag like an anchor tag, paragraph tag, span, div, or textarea.
If you have jQuery then:
$('#elName').empty();
Otherwise:
var node = document.getElementById('elName'); while (node.hasChildNodes()) { node.removeChild(node.firstChild); }
The Prototype way is Element.update()
e.g.:
$('my_container').update()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With