Assigning a string of HTML tags to a JavaScript variable, in addition to the value of the attribute to escape the double-cited extra, some time the string is still very long, it seems a little complicated. If you add elements dynamically with JS, there will be no more complicated strings appearing, code reading is a bit more readable, and it is easy to understand.
Web pages are made up of layers of HTML tags, and JS can dynamically add layers of tags such as div, Li, img. In fact, no matter what HTML tags, js dynamic creation of the method is similar, and then first from the dynamic Add div start.
First, JS dynamic add element div
<id= "parent"></div> function Addelementdiv (obj) {var parent = document.getElementById (obj); Add div var div = document.createelement ("div"); Set Div attributes, such as ID div.setattribute ("id", "newdiv"); div.innerhtml = "js dynamic add div"; Parent.appendchild (DIV); Call: Addelementdiv ("parent");
Second, JS dynamic add Li
<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 dynamic add Li"; Ul.appendchild (LI); Call: Addelementli ("Parentul");
Third, JS dynamic add element img
<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 property, such as ID img.setattribute ("id", "newimg"); Set img Image Address IMG.SRC = "/images/prod.jpg"; Li.appendchild (IMG); Ul.appendchild (LI); Call: Addelementimg ("Parentul");
Reprint: http://www.liangshunet.com/ca/201408/336848696.htm
JS Dynamic add elements (div, Li, img, etc.) and set properties