Replacing all children of an HTMLElement?

后端 未结 6 2024
爱一瞬间的悲伤
爱一瞬间的悲伤 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: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();
    }
    

提交回复
热议问题