Example of dynamically adding Li elements in javaScript, javascriptli
Html code block
<! DOCTYPE html>
Add Li element code dynamically in js (method 1)
Var userName = "Tom"; var userEamil = "12345678@qq.com"; var userPhone = "12345678910"; // Method 1: Use innerHTMLdocument. getElementById ("J_List "). innerHTML + = "<li class = \" newLi \ "> <span>" + _ userName + "<\/span> <span>" + userEamil + "<\/span> <span> "+ userPhone +" <\/span> <input type = \ "button \" value = \ "delete \" onclick = \ "this. parentNode. parentNode. parentNode. removeChild (this. parentNode. parentNode) \ "\/> <\/span> <\/li> ";
Add Li element code dynamically in js (method 2)
// Method 2: Use createElement to create a li element, setAttribute to set the element attributes, and appendChild () to add the element to the last child node of the parent element. // Create a li tag, including the display name, email address, phone number, and delete button. function addLi (useName, useEamil, usePhone) {var li_1 = document. createElement ("li"); li_1.setAttribute ("class", "newLi"); addSpan (li_1, userName); addSpan (li_1, userEamil); addSpan (li_1, userPhone ); addDelBtn (li_1); document. getElementById ("J_List "). appendChild (li_1);} // Add a span tag for the name or email address. Set the style function addSpan (li, text) {var span_1 = document. createElement ("span"); span_1.innerHTML = text; li. appendChild (span_1);} // Add the delete button, set the style of the delete button, and add and click the event function addDelBtn (li) {var span_1 = document. createElement ("span"); var btn = document. createElement ("button"); btn. setAttribute ("type", "button"); btn. setAttribute ("class", "delBtn"); btn. setAttribute ("onclick", "delBtnData (this)"); btn. innerHTML = "delete"; span_1.appendChild (btn); li. appendChild (span_1);} // Add the delete node function for the delete button delBtnData (obj) {var ul = document. getElementById ("J_List"); var oLi = obj. parentNode. parentNode; // obj. parentNode refers to the span layer of the delete button // obj. parentNode. parentNode is the ul of the li layer. removeChild (oLi );}
Knowledge point:InnerHTML (pay attention to double quotation marks "or \ need/escape ).
Knowledge point:CreateElement: creates an element. setAttribute: sets the element attribute. innerHTML sets the element value. appendChild adds an element. parentNode obtains the parent node (parentNode is W3C standard and parentElement is only available in IE .), removeChild deletes a subnode.
The above example of dynamically adding Li elements in javaScript is all the content shared by Alibaba Cloud xiaobian. I hope to give you a reference and support for the help house.