So im just testing a basic functionality on JavaScript. Im trying to set the <li>
within the <ul>
but for some simple reason my li
gets placed outside the ul
.
var test = document.getElementById('testdiv');
var data = [1,2,3,4,5];
test.innerHTML += '<ul>';
for (var i = 0; i < data[i]; i++)
{
test.innerHTML += '<li>' + i + '=' + data[i] + '</li>';
}
test.innerHTML += '</ul>';
.start{
border: 1px solid #000;
}
<div class="start" id="testdiv"></div>
Current html
outcome looks like this:
<div class="start" id="testdiv">
<ul></ul>
<li>0=1</li>
<li>1=2</li>
<li>2=3</li>
<li>3=4</li>
<li>4=5</li>
</div>
Expected outcome with an simple explanation would be much appreciated.
<div class="start" id="testdiv">
<ul>
<li>0=1</li>
<li>1=2</li>
<li>2=3</li>
<li>3=4</li>
<li>4=5</li>
</ul>
</div>
Appending to innerHTML is not supported: Usually, += is used for appending in JavaScript. But on appending to an Html tag using innerHTML, the whole tag is re-parsed.
To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.
'innerHTML' Presents a Security Risk The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.
@MikeChristensen explains why it is bad practice to use innerHtml
within for
loop.
Every time innerHTML is set, the HTML has to be parsed, a DOM constructed, and inserted into the document.
Try to use temporary string variable instead:
var myList = '<ul>';
for (var i = 0; i < data[i]; i++) {
myList += '<li>' + i + '=' + data[i] + '</li>';
}
myList += '</ul>';
test.innerHTML = myList;
Instead of using above approach you can use below one.
Possible reason is browser might adding the closing tag automatically to the opened tag.
var test = document.getElementById('testdiv');
var data = [1,2,3,4,5];
var ulelement = document.createElement("ul");
for (var i = 0; i < data[i]; i++)
{
ulelement.innerHTML += '<li>' + i + '=' + data[i] + '</li>';
}
test.appendChild(ulelement);
.start{
border: 1px solid #000;
}
<div class="start" id="testdiv"></div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With