简体   繁体   中英

How to append li and div tags to html using javascript dynamically

I am creating a horizontal timeline where the new element needs to be appended as per requirement.

I need to add new li,div tags to ol dynamically using javascript in below code This is my html code

<section class="timeline">
  <ol>
    <li>
      <div>
        <time>1934</time> mycode
      </div>
    </li>
  </ol>
</section>

I am new to technology. Could you please help.

What you need can be achieved using those methods from the document object.

1- let container = document.getElementById("YourContainerDiv"); which returns the container div element to append list items ( li ) to.

2- let listItem = document.createElement("li"); which returns a new element of list item.

3?- listItem.innerText = 'bla bla'; an optional step to populate your list item with data.

4- container.appendChild(listItem); which will add the newly created list item to the parent container element.

In order to dynamically create and append elements we have to use below methods to achieve what we need.

  1. document.createElement() - This method creates the HTML element with the tag name passed as parameter. example :create a li element:-

     var dynamicLi = document.createElement("li");
  2. element.setAttribute() - This method is use to set attribute. example - add id in the newly create li tag":-

     dynamicLI.setAttribute("id","li1");
  3. node.appendChild() - This method append a node to the end of the list of children of a specified parent node. example - add newly created li tag to its parent ul tag :-

     let ul = document.getElementById("dynamic-list"); // we get the parent node ul.appendChild(li); // we append the li in the ul tag.

So, below is the working code snippet, using step defined above:

  let ul = document.getElementById("Ul");  
  let li = document.createElement("li");
  li.setAttribute('id','li1');
  ul.appendChild(li);

Use this code.

var ul = document.getElementById("list");
  var li = document.createElement("li");
  li.appendChild(document.createTextNode("timeline"));
  ul.appendChild(li);

for jQuery see this reference:

Javascript to create an li and append to an ol

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM