JS Dynamic add elements (div, Li, img, etc.) and set properties

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.