Append multiple items in JavaScript

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

    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.

提交回复
热议问题