SoFunction
Updated on 2025-03-06

JavaScript dynamically adds instances of Li elements

html code block

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
   <title>**javaScriptDynamically addedLielement**</title>
   <style type="text/css">
 ul li{list-style:none;display:block;text-align:left;}
ul li span{display:inline-block;margin-top:5px;margin-right:35px;}
  </style>
   <script type="text/javascript">
   //add code
   </script>
   <body>
   // Here we dynamically add li elements for ul   <ul >
   </ul> 
   </body>
</html>

js dynamically add Li element code (Method 1)

 var userName="Tom";
 var userEamil="12345678@";
 var userPhone="12345678910";
 //Method 1: Use innerHTML("J_List").innerHTML+="<li class=\"newLi\"><span>"+_userName+"<\/span><span>"+userEamil+"<\/span><span>"+userPhone+"<\/span><span><input type=\"button\" value=\"delete\" onclick=\"
()\" \/><\/span><\/li>";

js dynamically add Li element code (Method 2)

//Method 2: Create a li element with createElement, then set the element attributes through setAttribute, and finally add it to the last child node of the parent element through appendChild() method. //Create a li tag, including display name, email, phone number and delete button   function addLi(useName,useEamil,usePhone){
    var li_1=("li");
    li_1.setAttribute("class","newLi");
    addSpan(li_1,userName);
    addSpan(li_1,userEamil);
    addSpan(li_1,userPhone);
    addDelBtn(li_1);
("J_List").appendChild(li_1);
   }
   //Add a span tag for your name or email address to set the style   function addSpan(li,text){
   var span_1=("span");
    span_1.innerHTML=text;
    (span_1);
   }
  //Add delete button, set the style of the delete button and add click event   function addDelBtn(li){
   var span_1=("span");
   var btn=("button");
   ("type","button");
   ("class","delBtn");
   ("onclick","delBtnData(this)");
   ="delete";
   span_1.appendChild(btn);
   (span_1);
   }
   //Add a delete node function for the delete button   function delBtnData(obj){
   var ul=("J_List");
    var oLi=; 
    //Refers to the span layer of the delete button    // is the li layer    (oLi);
   }  

Knowledge points:innerHTML (requires double quotes" or \ requires / escape).

Knowledge points:createElement creates the element, setAttribute sets the element attribute, innerHTML sets the element value, appendChild adds the element, parentNode gets the parent node (parentNode is W3C standard, parentElement is only available in IE.), removeChild deletes the child node.

The above example of dynamically adding Li elements in JavaScript is all the content I share with you. I hope you can give you a reference and I hope you can support me more.