Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
175
rated 0 times [  178] [ 3]  / answers: 1 / hits: 184763  / 8 Years ago, fri, april 22, 2016, 12:00:00

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() ?


More From » html

 Answers
5

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.


[#62437] Wednesday, April 20, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;