Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
269 views
in Technique[技术] by (71.8m points)

What is the best way to empty a node in JavaScript

I have a gallery with a long list of thumbnails. To prevent the DOM to be filled up with nodes, I am reusing them. What is the best way to remove the nodes from the DOM (without using a library)?

Using innerHTML = "" will parse and create a new empty text node, but looping and removing child will cause reflows?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You have at least four options:

  1. Using innerHTML = "" as you've shown in the question. It will make sure the element on which you call it has no child nodes at all, and doesn't create any new nodes. It's specified and reliable cross-browser (although there's an IE bug that may or may not affect your code), and is probably fairly efficient.

  2. Using textContent = "", which is also specified and reliable cross-browser (IE9+) and, interestingly, IE11 (at least) doesn't seem to have the bug with textContent that it has with innerHTML. It also has the advantage of not requiring an HTML parser, where of course the string you give innerHTML is expected to be HTML. (Browsers may well have an optimization in place for when the string is blank, though.)

  3. You could use removeChild in a loop, but that involves potentially repeated function calls into the DOM:

    // assuming elm is the element
    while (elm.firstChild) {
       elm.removeChild(elm.firstChild);
    }
    
  4. You could replace the parent element with a clone omitting the children:

    // assuming elm is the element
    const clone = elm.cloneNode(false);
    parent.parentElement.replaceChild(clone, elm);
    elm = clone;
    

    Note that unlike the others, this will remove any event handlers on the parent element.

If I had to guess, I'd guess that textContent = "" would be fastest, at least if there are a lot of children. But performance usually doesn't matter, it's an extremely rare case where this will be the noticeably slow part of your code. If you run into a situation where it matters, test your actual code usihng each of the options in your target browsers and choose the one that works best.

People love synthetic benchmarks, but synthetic benchmarks are remarkably unreliable and sensitive to benchmark assumptions (such as the number of children being removed).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...