Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I clear the contents of a div without innerHTML = "";

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?

like image 204
Myles Gray Avatar asked Feb 20 '11 14:02

Myles Gray


People also ask

How do I empty the content of a div?

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.

What can we use instead of innerHTML?

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?

Why you shouldn't use innerHTML?

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 .

Is innerHTML necessary?

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.


2 Answers

If you have jQuery then:

$('#elName').empty(); 

Otherwise:

var node = document.getElementById('elName'); while (node.hasChildNodes()) {     node.removeChild(node.firstChild); } 
like image 58
Alnitak Avatar answered Sep 24 '22 02:09

Alnitak


The Prototype way is Element.update() e.g.:

$('my_container').update() 
like image 41
Antonio Bardazzi Avatar answered Sep 23 '22 02:09

Antonio Bardazzi