The following section describes how to dynamically add elements (div, li, img, etc.) and set attributes in js. I think it sounds good. Now I will share it with you and give you a reference. Let's take a look at the small Editor and assign a string of html tags to a javascript variable. In addition to the attribute value, the double quotation marks must be escaped. In some cases, the string is still very long and complicated. If Javascript is used to dynamically add elements, there will be no complicated strings, and the code is more readable and easy to understand.
A webpage consists of html tags. js can also dynamically add tags such as p, li, and img. In fact, no matter what html tags, js dynamic creation methods are similar, and then start from dynamic addition of p.
I. Add element p dynamically in js
Function addElementDiv (obj) {var parent = document. getElementById (obj); // Add p var p = document. createElement ("p"); // set the p attribute, such as id p. setAttribute ("id", "newDiv"); p. innerHTML = "js dynamic add p"; parent. appendChild (p );}
Call: addElementDiv ("parent ");
Ii. dynamically Add li in js
Function addElementLi (obj) {var ul = document. getElementById (obj); // Add li var li = document. createElement ("li"); // sets the li attribute, such as id li. setAttribute ("id", "newli"); li. innerHTML = "Add li dynamically in js"; ul. appendChild (li );}
Call: addElementLi ("parentUl ");
Iii. dynamically add element img in js
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"); // you can specify the img image address. src = "/images/prod.jpg"; li. appendChild (img); ul. appendChild (li );}
Call: addElementImg ("parentUl ");
The above js dynamic addition of elements (p, li, img, and so on) and the method of setting attributes is all the content shared by the editor, and I hope to give you a reference, I also hope that you will support PHP.
For more articles about how to dynamically add elements (p, li, img, etc.) and set attributes in js, please follow the PHP Chinese website!