简体   繁体   中英

Adding new <li> element into <ul> Questions

this is my html code

 function addChildren() { var el = document.getElementById('one'); //Create new node and textNode var newEl = document.createElement('li'); var newText = document.createTextNode('New Node Text'); //Append as child Node newEl.appendChild(newText); newEl.setAttribute('class', 'hot'); //Append as child Node to the last of list el.appendChild(newEl); //Append as child node to the beginning of list el.insertBefore(newEl, el.firstChild); } document.querySelector('#add'). addEventListener('click', addChildren);
 <ul id='one'> <li class='hot'>Hello</li> <li class='hot'>World</li> <li class='hot'>This</li> <li class='hot'>Is</li> <li class='hot'>Ben!</li> </ul> <button id="add">Add</button>

Why is the script only executing 1 insertion of the new element, although I put in 2 (insertBefore and appendChild)?

And when I tried adding multiple 'appendChild()' method, only 1 new element is added, why is this?

You are trying to add the same node in two places, so the last one wins. The node is actually added to the end, but immediately moved to the start.

You canclone the node, and insert the clone to the start:

 function addChildren() { var el = document.getElementById('one'); //Create new node and textNode var newEl = document.createElement('li'); var newText = document.createTextNode('New Node Text'); //Append as child Node newEl.appendChild(newText); newEl.setAttribute('class', 'hot'); //Append as child Node to the last of list el.appendChild(newEl); // create a clone of the node var clone = newEl.cloneNode(true); //Append the clone as child node to the beginning of list el.insertBefore(clone, el.firstChild); } document.querySelector('#add'). addEventListener('click', addChildren);
 <ul id='one'> <li class='hot'>Hello</li> <li class='hot'>World</li> <li class='hot'>This</li> <li class='hot'>Is</li> <li class='hot'>Ben!</li> </ul> <button id="add">Add</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM