Home > Web Front-end > JS Tutorial > body text

How to dynamically add elements (div, li, img, etc.) and set attributes in js

高洛峰
Release: 2016-12-24 15:11:51
Original
1919 people have browsed it

Assign a string of html tags to a javascript variable. In addition to the attribute value using escaped double quotes, sometimes the string is very long and seems a bit complicated. If you use js to dynamically add elements, there will be no such complicated strings, and the code will be more readable and easier to understand.

Web pages are composed of layers of html tags, 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 dynamically creating it in js is the same. Then we start by dynamically adding div.

1. js dynamically add element div

<div id="parent"></div>
 
  function addElementDiv(obj) {
    var parent = document.getElementById(obj);
 
    //添加 div
    var div = document.createElement("div");
 
    //设置 div 属性,如 id
    div.setAttribute("id", "newDiv");
 
    div.innerHTML = "js 动态添加div";
    parent.appendChild(div);
  }
Copy after login

call: addElementDiv("parent");

3. Dynamically add element img in js

<ul id="parentUl"><li>原li</li></ul>
 
  function addElementLi(obj) {
    var ul = document.getElementById(obj);
 
    //添加 li
    var li = document.createElement("li");
 
    //设置 li 属性,如 id
    li.setAttribute("id", "newli");
 
    li.innerHTML = "js 动态添加li";
    ul.appendChild(li);
  }
Copy after login

Call: addElementImg("parentUl");

The above method of dynamically adding elements (div, li, img, etc.) and setting attributes in js is shared by the editor I’ve given you all the content, I hope it can give you a reference, and I hope you will support the PHP Chinese website.

For more js dynamically adding elements (div, li, img, etc.) and methods of setting attributes, please pay attention to the PHP Chinese website for related articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!