1

I have the following code below, where I am trying to create a ul tag, and inside it a for loop to dynamically create li elements. A separate closing ul tag is created after the loop is completed.

The code works. Except for the problem that the code does not run in order like I want it to. The ul tags are closed before the for loop can be processed into the page, resulting in the html looking more like:

<ul></ul><li>0</li><li>1</li>...

var insidethediv = document.getElementById("insidethediv");
var numero = 5;

insidethediv.innerHTML = "<ul>";
for (i = 0; i < 5; i++){
insidethediv.innerHTML += "<li>"+i+"</li>";
}
insidethediv.innerHTML += "</ul>";
<div id="insidethediv"></div>

2 Answers 2

2

Assigning directly to innerHTML is a bad idea here. innerHTML expects a complete html fragment, i.e. all open tags should be closed. But here you are assigning to a partial html fragment while you are building it. Try to create the complete html first and then assign it to innerHTML, e.g. like so:

var insidethediv = document.getElementById("insidethediv");
var numero = 5;

var s = "<ul>";
for (i = 0; i < 5; i++){
    s += "<li>"+i+"</li>";
}
s += "</ul>";
insidethediv.innerHTML = s;
Sign up to request clarification or add additional context in comments.

Comments

1

I personally prefer to use document.createElement(tag name) and Element.append(created element reference) functions. In this way we are able to manipulate each individual <li> tag (such as assign different colors) and render the HTML tags dynamically instead of jamming everything into a string then insert it as an innerHTML element.

var insidethediv = document.getElementById("insidethediv");
var numero = 5;

var ul_element = document.createElement("ul");
insidethediv.append(ul_element);

var li_element;

for (var i = 0; i < 5; i++){
    li_element = document.createElement("li");
    ul_element.append(li_element);
    li_element.innerHTML = i;
}
<div id="insidethediv"></div>

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.