js Dynamic Adding Elements of div li img and the Method of Setting Attributes

  • 2021-07-04 17:56:10
  • OfStack

Assigning a string of html tags to an javascript variable, in addition to using escaped double quotation marks for the value of the attribute, sometimes the string is very long and somewhat complicated. If you add elements dynamically with js, there will be no such complex strings, and the code is 1 point readable and easy to understand.

Web pages are composed of html tags 1 layer, and js can also dynamically add 1 layer of tags such as div, li and img. In fact, no matter what html tag it is, the dynamic creation method of js is similar, and then start by dynamically adding div.

1. js dynamically add element div


<div id="parent"></div>

    function addElementDiv(obj) {
          var parent = document.getElementById(obj);

          // Add  div
          var div = document.createElement("div");

          // Settings  div  Attributes, such as  id
          div.setAttribute("id", "newDiv");

          div.innerHTML = "js  Dynamic addition div";
          parent.appendChild(div);
    }

Call: addElementDiv ("parent");

2. js dynamically adds li


<ul id="parentUl"><li> Original li</li></ul>

    function addElementLi(obj) {
          var ul = document.getElementById(obj);

          // Add  li
          var li = document.createElement("li");

          // Settings  li  Attributes, such as  id
          li.setAttribute("id", "newli");

          li.innerHTML = "js  Dynamic addition li";
          ul.appendChild(li);
    }

Call: addElementLi ("parentUl");

3. js Dynamic Addition Element img


<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");

          // Settings  img  Attributes, such as  id
          img.setAttribute("id", "newImg");

          // Settings  img  Picture address 
          img.src = "/images/prod.jpg";

          li.appendChild(img);
          ul.appendChild(li);
    }

Call: addElementImg ("parentUl");


Related articles: