Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove child nodes (or elements) or set innerHTML=""?

Tags:

javascript

dom

When clearing HTML elements such as select boxes, tables, or lists, is it better/faster to remove the nodes (e.g., select.options.remove(i), table.deleteRow(i)) or just empty the innerHTML (e.g., select.innerHTML = "")? Or does it matter?

An example case would be reinitializing a table. A specific select field's value should load different values for a subsequent HTML table. When the select value changes, the table needs to be reinitialized.

like image 361
reformed Avatar asked Aug 06 '13 15:08

reformed


People also ask

How do you remove child nodes?

Child nodes can be removed from a parent with removeChild(), and a node itself can be removed with remove(). Another method to remove all child of a node is to set it's innerHTML=”” property, it is an empty string which produces the same output.

Does innerHTML remove event listeners?

Please note that using innerHTML to append HTML elements (e.g. el.innerHTML += "<a href='…'>link</a>" ) will result in the removal of any previously set event listeners. That is, after you append any HTML element that way you won't be able to listen to the previously set event listeners.

How do you remove all children from an element?

To remove all child nodes of an element, you can use the element's removeChild() method along with the lastChild property. The removeChild() method removes the given node from the specified element. It returns the removed node as a Node object, or null if the node is no longer available.

How do I remove spaces from innerHTML?

Replace all spaces in innerHTML content using trim() and replace() functions.


1 Answers

In IE you cannot set the innerHTML of a select element. So for a cross-browser solution the only way is to add/remove child nodes.

like image 137
Christophe Avatar answered Sep 19 '22 10:09

Christophe