Skip to content
Advertisement

JS append elements

I am generating some <li> with JS into my list. This <li> consist from few elements, such as <div>, <section>, etc.

//here I get my <ul>
let list = document.getElementById('list');

//here I generate 5 <li>
for (let li = 0; li < 5; li++){
    let li_wrapp = document.createElement('li');
   
    //here I take together some elements in <li>. Part of my question.
    for (let li_elements = 0; li_elements < 5; li_elements++){
       li_wrapp.appendChild(document.createElement('div');
    }
    list.appendChild(li_wrapp);
}

And my question is. For now, I generate exact number of elements into the array and then I append these elements from that array. But I would like to know, if I am able to append something on that div, which created in for cycle which is above. In my code right now, I just created 5 divs in array, and I am appending to them.

//here I get my <ul>
let list = document.getElementById('list');

//here I generate 5 <li>
for (let li = 0; li < 5; li++){
    let li_wrapp = document.createElement('li');
    let div_array = [];
   
    //here I take together some elements.
    for (let li_elements = 0; li_elements < 5; li_elements++){
       //here I create div in array
       div_array[li_elements] = document.createElement('div');
       //here I append that div to wrapper
       li_wrapp.appendChild(div_array[li_elements]);
       //and here I am able to append something to that div. 
       div_array[li_elements].append.... etc
    }
    list.appendChild(li_wrapp);
}

But this solution looks pretty ugly to me. Isn’t here another way how to make this easier and more efficiently? Because if I want to make a <li> with more elements, it’s a pretty huge block of code.

Advertisement

Answer

Because Node.appendChild() returns the appended element, the code you have can be simplified as follows by chaining the calls:

const ul = document.getElementById('list');

for (let i = 0; i < 5; i++) {
  ul.appendChild(document.createElement('li'))
    .appendChild(document.createElement('div'));
}
<ul id="list"></ul>

Another alternative would be to build the li structure once, and then create 5 deep clones using Node.cloneNode().

const ul = document.getElementById('list');

const li = document.createElement('li');
li.appendChild(document.createElement('div'));

for (let i = 0; i < 5; i++) {
  ul.appendChild(li.cloneNode(true));
}
<ul id="list"></ul>

In addition to the suggestions outlined above, it might also be worthwhile to look into ParentNode.append() because it allows you to append multiple elements at once.

Everything considered though, you should probably be looking into frameworks like Angular, React or Vue. jQuery also has some utilities that can make this easier, but recommending jQuery in 2020 is not very much in keeping with the times…

Advertisement