Append Multiple Items In JavaScript


Answer :

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


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

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.


Comments

Popular posts from this blog

Are Regular VACUUM ANALYZE Still Recommended Under 9.1?

Can Feynman Diagrams Be Used To Represent Any Perturbation Theory?