简体   繁体   中英

Javascript appendChild not working for li element

My JavaScript code works up to the last append . This I checked with alert messages. All the alerts except for the last one get displayed. So I assume the problem is with the last append . Can someone please help?

 var node = document.createElement("li"); var d0 = document.createElement("div"); var d1 = document.createElement("div"); var L1 = document.createElement("label"); d1.append(L1); L1.innerHTML = "datah[key]"; var d2 = document.createElement("div"); var L2 = document.createElement("label"); d2.append(L2); L2.innerHTML = "datah1[key]"; console.log("test1"); d0.append(d1); d0.append(d2); node.append(d0); console.log("test2"); document.getElementById("speclist").appendChild(node); // The following alert doesn't get printed console.log("test3"); 
 <div> <ul id="speclist"> </ul> </div> 

There is no problem with last append problem is that you are not wrapping "test3" in any html.you want to show test3 then you have to wrap it with node(li).

 var node = document.createElement("li"); var d0 = document.createElement("div"); var d1 = document.createElement("div"); var L1 = document.createElement("label"); d1.append(L1); L1.innerHTML = "datah[key]"; var d2 = document.createElement("div"); var L2 = document.createElement("label"); d2.append(L2); L2.innerHTML = "datah1[key]"; alert("test1"); d0.append(d1); d0.append(d2); node.append(d0); alert("test2"); //document.getElementById("speclist").appendChild(node); // The following alert doesn't get printed alert("test3"); node.appendChild(document.createTextNode("test3")); document.getElementById("speclist").appendChild(node); 
 <div> <ul id="speclist"> </ul> </div> 

and one more thing when i am running your code it is showing me 3 alerts test1,test2 and test3.

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