What is a more efficient way to remove all children of an HTML element?

I know that accessing and manipulating the DOM can be very expensive, so I want to do this as efficiently as possible. My situation is that a particular div will always contain a list of elements, however sometimes I want to update this list with a completely different set of elements. In this case, I can create a new list and add it to this div, but I also need to clear the list. What is the best way? Set innerHTML to an empty string? Iterate over child nodes and call "removeChild"? Something else?

+3
source share
4 answers

Take a look at QuirksMode . This may take some time, but there are times for this operation in different browsers. Although the tests were performed more than a year ago, installation innerHTMLin ""was the fastest in most browsers.

PS here is a page.

+6
source

set innerHTML to an empty string.

0
source

. ; , , . , , , , , , .

innerHTML, ; - DOM, - .

99,9% , DOM:

while(ele.childNodes.length > 0) {
    ele.removeChild(ele.childNodes[ele.childNodes.length - 1])
}
0

, . Javascript- , DOM . .

0

Source: https://habr.com/ru/post/1702800/


All Articles