Replacing all children of an HTMLElement?

后端 未结 6 1954
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-02-05 00:40

In my code, I fairly frequently need to replace all children of a certain HTML container with a new list of children.

What is the fastest way to do this? My current appr

相关标签:
6条回答
  • 2021-02-05 01:14

    from the top answer, we could also use outerHTML to do it in one line.

    container.innerHTML = newContainerElements.outerHTML
    
    0 讨论(0)
  • 2021-02-05 01:17

    Use modern JS! Directly use remove rather than removeChild

    while (container.firstChild) {
        container.firstChild.remove();
    }
    

    Alternatively:

    let child;
    while (child = container.firstChild) {
        child.remove();
    }
    
    0 讨论(0)
  • 2021-02-05 01:17

    2020 Update - use the replaceChildren() API!

    Replacing all children can now be done with the (cross-browser supported) replaceChildren() API:

    container.replaceChildren(...arrayOfNewChildren);
    

    This will do both: a) remove all existing children, and b) append all of the given new children, in one operation.

    You can also use this same API to just remove existing children, without replacing them:

    container.replaceChildren();
    

    This is supported in Chrome/Edge 86+, Firefox 78+, Safari 14+, and eventually the rest. It is fully specified behavior. This is likely to be faster than any other proposed method here, since the removal of old children and addition of new children is done a) without requiring innerHTML, and b) in one step instead of multiple.

    0 讨论(0)
  • 2021-02-05 01:19

    If you simply want to replace all children, regarding of the type, why don't you just set its content to '' and then add your code:

    container.innerHTML = '';
    container.appendChild( newContainerElements );
    

    that would basically remove all the children in the fastest possible way :)

    0 讨论(0)
  • 2021-02-05 01:20

    A possible alternative where setting innerHTML doesn't work:

    while(container.firstChild)
    {
      container.removeChild(container.firstChild);
    }
    container.appendChild(newChild)
    
    0 讨论(0)
  • 2021-02-05 01:33

    It is not directly solving the question but in most cases it is usable and probably one of the more performant ways.

    You can swap out the whole node instead of deleting and filling its content.

    oldNode.parentElement.replaceChild(newNode, oldNode)

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