Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do you add an `li` tag only data exists in an array in html/css/javascript?

I am brand new to HTML/CSS/Javascript fyi. So I have a list of items in html using an ul tag and multiple li tags. I don’t understand how I am only able to add an li if there is data that exists.

For example: I am using firebase as my backend. Lets say we have a list saved to firebase called myList:

myList = ["dog", "cat", "pig"]

So right now if i was going to use this list I would need 3 li tags.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<ul>
  <li>dog</li>
  <li>cat</li>
  <li>pig</li>
</ul>

But lets say another user adds a 4th element called "cow". So now myList equals:

myList = ["dog", "cat", "pig", "cow"]

I only have 3 li tags so how do I now add a 4th one to my code so it will present cow in the list? I understand in other languages you could just use a for loop for however many data points there are in your list, but html doesn’t have for loops so how do I do this?

>Solution :

use this example

var node = document.createElement("LI");      // Create a <li> node

var textnode = document.createTextNode("Water");  // Create a text node

node.appendChild(textnode);                      // Append the text to <li>

document.getElementById("myList").appendChild(node);  // Append <li> to <ul> with id="myList"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading