Append multiple items in JavaScript

后端 未结 9 400
长情又很酷
长情又很酷 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:44

    You can use createContextualFragment, it return a documentFragment created from a string. It is perfect if you have to build and append more than one Nodes to an existing Element all together, because you can add it all without the cons of innerHTML

    https://developer.mozilla.org/en-US/docs/Web/API/Range/createContextualFragment

    // ...
    var listItem = document.createElement("li");
    var documentFragment = document.createRange().createContextualFragment(`
        <input type="checkbox">
        <label>Content typed by the user</label>
        <input type="text">
        <button class="edit">Edit</button>
        <button class="delete">Delete</button>
    `)
    listItem.appendChild(documentFragment)
    // ...
    
    0 讨论(0)
  • 2020-12-07 21:47

    You can use the append method in JavaScript.

    This is similar to jQuery's append method but it doesnot support IE and Edge.

    You can change this code

    listElement.appendChild(listItem);
    listItem.appendChild(listItemCheckbox);
    listItem.appendChild(listItemLabel);
    listItem.appendChild(editButton);
    listItem.appendChild(deleteButton);
    

    to

    listElement.append(listItem,listItemCheckbox,listItemLabel,editButton,deleteButton);
    
    0 讨论(0)
  • 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]);
    
    0 讨论(0)
提交回复
热议问题