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

后端 未结 3 1158
鱼传尺愫
鱼传尺愫 2021-01-18 21:27

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.deleteR

相关标签:
3条回答
  • 2021-01-18 21:39

    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.)

    0 讨论(0)
  • 2021-01-18 21:47

    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.

    0 讨论(0)
  • 2021-01-18 21:55

    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.

    0 讨论(0)
提交回复
热议问题