Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding to innerHTML after JavaScript for loop

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>
like image 386
Ylama Avatar asked Jan 09 '18 13:01

Ylama


People also ask

Can you += innerHTML?

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.

Can you append to innerHTML?

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.

Why you shouldn't use 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.


2 Answers

@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;
like image 103
Alexander Avatar answered Sep 26 '22 13:09

Alexander


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>
like image 26
Lalit Avatar answered Sep 25 '22 13:09

Lalit