abrahamlinkedin
abrahamlinkedin

Reputation: 467

Append dynamic li from an array

I have been spoiled by frameworks and would like to know how plain ol' Javascript handles this. Basically, I would like my JavaScript to output a list that contains all items from my array. The code is as follows:

javascript

function addrain(){
    var element = ['apple', 'orange', 'banana'];
    for (var i = 0; i < element.length; i++){ 
    //what goes here??//
    document.getElementById('listcontent').append...
});
}

html

<ul id="listcontent"></ul>

Upvotes: 1

Views: 2712

Answers (4)

Md Mahmood Bin Habib
Md Mahmood Bin Habib

Reputation: 71

const elements = ["orange", "apple", "banana"];

const list_element_to_insert = document.getElementById('listcontent'); // get the html element

// i have used mapping first to create a li element. then transform the 
// returned map list into string by join
list_element_to_insert.innerHTML = `${elements.map(element => `<li>${element}</li>`).join('')}`; 
<ul id="listcontent"></ul>

Upvotes: 0

Freyja
Freyja

Reputation: 40804

Use document.createElement to create elements, element.textContent to fill them with text and parent.appendChild to add it to its parent element.

You can also use element.innerHTML or element.appendChild instead of element.textContent if you want your <li> elements to contain more HTML than just plain text.

Here's an runnable example, based on your code:

function addrain() {
  var element = ['apple', 'orange', 'banana'];
  for (var i = 0; i < element.length; i++) {
    // Create DOM element
    var li = document.createElement('li');
        
    // Set text of element
    li.textContent = element[i];

    // Append this element to its parent
    document.getElementById('listcontent').appendChild(li);
  }
}

addrain();
<ul id="listcontent"></ul>

Upvotes: 2

Nick Zuber
Nick Zuber

Reputation: 5637

You just need to create a DOM element for each item, and then append that element to your list.

function addrain(){
    var element = ['apple', 'orange', 'banana'];
    for (var i = 0; i < element.length; i++){ 

      // Create DOM element
      let childNode = document.createElement('li');

      // Set content to current element
      childNode.innerHTML = element[i];

      // Add DOM Node to list
      document.getElementById('listcontent').appendChild(childNode);
    }
}

addrain();
<ul id="listcontent"></ul>

Upvotes: 4

Andrew
Andrew

Reputation: 3381

Try using this as your function:

function addrain(){
    var element = ['apple', 'orange', 'banana'];
    for (var i = 0; i < element.length; i++){ 
        var li = document.createElement('li'); // Create an <li>
        li.appendChild(document.createTextNode(element[i])); // Add the name of the fruit
        document.getElementById('listcontent').appendChild(li); // Append the <li> to the <ul>
    }
}

https://jsfiddle.net/xcqegL3b/

Upvotes: 1

Related Questions