abrahamlinkedin abrahamlinkedin - 1 year ago 96
Javascript Question

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:


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


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

Answer Source

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download