简体   繁体   中英

Remove child nodes (or elements) or set innerHTML=“”?

When clearing HTML elements such as select boxes, tables, or lists, is it better/faster to remove the nodes (eg, select.options.remove(i) , table.deleteRow(i) ) or just empty the innerHTML (eg, 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.

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.

I made a new test that isn't broken.

http://jsperf.com/innerhtml-vs-removechild/67

It's not perfect either since part of the sample setup is part of the test so this might skew the results.

This gives that innerHTML is faster but I don't know by how much.

Per this conversation here: What is the best way to empty an node in JavaScript

It appears that the while (elm.firstChild) {elm.removeChild(elm.firstChild);} approach got the the best results across browsers in this test .

(Would have put this as a comment instead of an answer, but the comments are coming in awful fast, so I didn't want it to get lost.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM