Append multiple items in JavaScript

后端 未结 9 401
长情又很酷
长情又很酷 2020-12-07 20:58

I have the following function and I am trying to figure out a better way to append multiple items using appendChild().

When the user clicks on Add, each

9条回答
  •  独厮守ぢ
    2020-12-07 21:52

    Merging the answers by @Atrahasis and @Slavik:

    if (Node.prototype.appendChildren === undefined) {
      Node.prototype.appendChildren = function() {
        let children = [...arguments];
    
        if (
          children.length == 1 &&
          Object.prototype.toString.call(children[0]) === "[object Array]"
        ) {
          children = children[0];
        }
    
        const documentFragment = document.createDocumentFragment();
        children.forEach(c => documentFragment.appendChild(c));
        this.appendChild(documentFragment);
      };
    }
    

    This accepts children as multiple arguments, or as a single array argument:

    foo.appendChildren(bar1, bar2, bar3);
    bar.appendChildren([bar1, bar2, bar3]);
    

    Update – June 2020

    Most all current browsers support append and the "spread operator" now.

    The calls above can be re-written as:

    foo.append(bar1, bar2, bar3);
    bar.append(...[bar1, bar2, bar3]);
    

提交回复
热议问题