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.
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.
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.
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.
Replace all spaces in innerHTML content using trim() and replace() functions.
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.
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