1

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.

3

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

1 Comment

very well explained. 👍🏻
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.