简体   繁体   中英

DOM appendChild is not works for two variables

I am having the following code to write list element in js click function, for two divs(myList , myList1).

I am appending li child for both, but only second div gets updated but first div is not updated,

  function myFunction() { var node = document.createElement("LI"); var textnode = document.createTextNode("Water"); node.appendChild(textnode); document.getElementById("myList").appendChild(node); document.getElementById("myList1").appendChild(node); } 
 <!DOCTYPE html> <html> <body> <ul id="myList"> <li>Coffee</li> <li>Tea</li> </ul> <ul id="myList1"> <li>Coffee</li> <li>Tea</li> </ul> <button onclick="myFunction()">Try it</button> </body> </html> 

It produces the following output,

myList:
    -------
Coffee
Tea

myList1:
    -------
Coffee
Tea
Water

Actual output I am looking for is as follows,

myList:
    -------
Coffee
Tea
Water

myList1:
    -------
Coffee
Tea
Water

I am missing something here, can someone suggest what it is.

Thanks in advance.

It is because appendchild moves the node from first to second ul.

this line

document.getElementById("myList").appendChild(node);

add the node to ul myList but the very next line

document.getElementById("myList1").appendChild(node);

moves the node from myList to myList1

You can clone your node to get the desired result.

 <!DOCTYPE html> <html> <body> <ul id="myList"> <li>Coffee</li> <li>Tea</li> </ul> <ul id="myList1"> <li>Coffee</li> <li>Tea</li> </ul> <button onclick="myFunction()">Try it</button> <script> function myFunction() { var node = document.createElement("LI"); var textnode = document.createTextNode("Water"); node.appendChild(textnode); var newNode = node.cloneNode(true); document.getElementById("myList").appendChild(node); document.getElementById("myList1").appendChild(newNode); } </script> </body> </html> 

As your question has a jQuery tag, you should try this:

 function myFunction() { node = $('<li/>').html("water") $('ul').append(node) } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <ul id="myList"> <li>Coffee</li> <li>Tea</li> </ul> <ul id="myList1"> <li>Coffee</li> <li>Tea</li> </ul> <button onclick="myFunction()">Try it</button> 

You cant append a node to multiple elems. You need to clone it:

var elem=document.createElement("Li");
//add text
elem2=elm.cloneNode(true);
//append to dom

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