Assign a string of html tags to a javascript variable. In addition to the escaped double quotes of the attribute value, the string is still very long and seems a bit complicated at some point. If you add elements dynamically with js, there will be no such complex strings, and the code is more readable and easy to understand.
Web pages are composed of html tags layer by layer, and js can also dynamically add layers of tags such as div, li, and img. In fact, no matter what html tag it is, the method of dynamic creation of js is similar. Then start by adding divs dynamically.
1. Add elements div dynamically in js
<div id="parent"></div> function addElementDiv(obj) { var parent = document.getElementById(obj); //Add div var div = document.createElement("div"); //Set the div attribute, such as id div.setAttribute("id", "newDiv"); div.innerHTML = "js dynamically add div"; parent.appendChild(div); }Call: addElementDiv("parent");
2. Add li dynamically to js
<ul id="parentUl"><li>Original li</li></ul> function addElementLi(obj) { var ul = document.getElementById(obj); //Add li var li = document.createElement("li"); //Set the li attribute, such as id li.setAttribute("id", "newli"); li.innerHTML = "js dynamically add li"; ul.appendChild(li); }Call: addElementLi("parentUl");
3. Add elements img dynamically in js
<ul id="parentUl"></ul> function addElementImg(obj) { var ul = document.getElementById(obj); //Add li var li = document.createElement("li"); //Add img var img = document.createElement("img"); //Set the img attribute, such as id img.setAttribute("id", "newImg"); //Set the img image address img.src = "/images/prod.jpg"; li.appendChild(img); ul.appendChild(li); }Call: addElementImg("parentUl");
The above article on js dynamically adding elements (div, li, img, etc.) and setting attributes is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.