Append multiple items in JavaScript

混江龙づ霸主 提交于 2019-12-29 04:15:10

问题


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 item should look like this:

<li>
  <input type="checkbox">
  <label>Content typed by the user</label>
  <input type="text">
  <button class="edit">Edit</button>
  <button class="delete">Delete</button>
</li>

and I have this function to add these elements:

function addNewItem(listElement, itemInput) {
  var listItem = document.createElement("li");
  var listItemCheckbox = document.createElement("input");
  var listItemLabel = document.createElement("label");
  var editableInput = document.createElement("input");
  var editButton = document.createElement("button");
  var deleteButton = document.createElement("button");

  // define types
  listItemCheckbox.type = "checkbox";
  editableInput.type = "text";

  // define content and class for buttons
  editButton.innerText = "Edit";
  editButton.className = "edit";
  deleteButton.innerText = "Delete";
  deleteButton.className = "delete";

  listItemLabel.innerText = itemText.value;

  // appendChild() - append these items to the li
  listElement.appendChild(listItem);
  listItem.appendChild(listItemCheckbox);
  listItem.appendChild(listItemLabel);
  listItem.appendChild(editButton);
  listItem.appendChild(deleteButton);

  if (itemText.value.length > 0) {
    itemText.value = "";
    inputFocus(itemText);
  }
}

But you can notice that I am repeating three times the appendChild() for listItem. Is it possible to add multiple items to the appendChild() ?


回答1:


Personally, I don't see why you would do this.

But if you really need to replace all the appendChild() with one statement, you can assign the outerHTML of the created elements to the innerHTML of the li element.

You just need to replace the following:

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

With the following:

listItem.innerHTML+= listItemCheckbox.outerHTML + listItemLabel.outerHTML + editButton.outerHTML + deleteButton.outerHTML;
listElement.appendChild(listItem);

Explanation:

The outerHTML attribute of the element DOM interface gets the serialized HTML fragment describing the element including its descendants. So assigning the outerHTML of the created elements to the innerHTML of the li element is similar to appending them to it.




回答2:


You can do it with DocumentFragment.

var documentFragment = document.createDocumentFragment();
documentFragment.appendChild(listItem);
listItem.appendChild(listItemCheckbox);
listItem.appendChild(listItemLabel);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
listElement.appendChild(documentFragment);

DocumentFragments allow developers to place child elements onto an arbitrary node-like parent, allowing for node-like interactions without a true root node. Doing so allows developers to produce structure without doing so within the visible DOM




回答3:


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);



回答4:


You need to append several children ? Just make it plural with appendChildren !

First things first :

HTMLLIElement.prototype.appendChildren = function () {

  for ( var i = 0 ; i < arguments.length ; i++ )

    this.appendChild( arguments[ i ] );

};

Then for any list element :

listElement.appendChildren( a, b, c, ... );

//check :
listElement.childNodes;//a, b, c, ...

Works with every element that has the appendChild method of course ! Like HTMLDivElement.




回答5:


You could just group the elements into a single innerHTML group like this:

  let node = document.createElement('li');
  node.innerHTML = '<input type="checkbox"><label>Content typed by the user</label>  <input type="text"><button class="edit">Edit</button><button class="delete">Delete</button>';
  document.getElementById('orderedList').appendChild(node);

then appendChild() is only used once.




回答6:


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)
// ...



回答7:


It's possible to write your own function if you use the built in arguments object

function appendMultipleNodes(){
  var args = [].slice.call(arguments);
  for (var x = 1; x < args.length; x++){
      args[0].appendChild(args[x])
  }
  return args[0]
}

Then you would call the function as such:

appendMultipleNodes(parent, nodeOne, nodeTwo, nodeThree)



回答8:


Merging the answers by @Atrahasis and @Slavik:

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]);



回答9:


I would like to add that if you want to add some variability to your html, you can also add variables like this:

let node = document.createElement('div');
node.classList.add("some-class");
node.innerHTML = `<div class="list">
                  <div class="title">${myObject.title}</div>
                  <div class="subtitle">${myObject.subtitle}
                </div>`;


来源:https://stackoverflow.com/questions/36798005/append-multiple-items-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!