AbsoluteBeginner
AbsoluteBeginner

Reputation: 2255

Alternative ways to dynamically create li elements

Using JavaScript, I need to dynamically create a list like this:

<ul id="list">
<li>2015</li>
<li>2016</li>
<li>2017</li>
<li>2018</li>
<li>2019</li>
<li>2020</li>
</ul>

The "classic solution" (as far as I know) is:

for (var i = 2015; i <= 2020; i++) {
  var li = document.createElement("li");
  li.innerHTML = i;
  list.appendChild(li);
}

It works perfectly.

But I would like to find alternative, better - in terms of performance - solutions, if there are (I want to learn something more).

So I tried:

for (var i = 2015; i <= 2020; i++) {
  var el = "<li>" + i + "</li>";
  list.insertAdjacentHTML('beforeend', el);
  console.log(el);
  el += el;
}
<ul id="list"></ul>

AND

for (var i = 2015; i <= 2020; i++) {
  var el = "<li>" + i + "</li>";
  list.innerHTML += el;
  console.log(el);
}
<ul id="list"></ul>

But in both cases this is the result:

<ul id="list">
<li>2015</li>
<li></li>
<li>2016</li>
<li></li>
<li>2017</li>
<li></li>
<li>2018</li>
<li></li>
<li>2019</li>
<li></li>
<li>2020</li>
<li></li>
</ul>
<li>2015<li>
<li>2016<li>
<li>2017<li>
<li>2018<li>
<li>2019<li>
<li>2020<li>

Why those empty nodes (<li></li>)? And why in the DOM only?

Upvotes: 0

Views: 28

Answers (1)

black blue
black blue

Reputation: 819

In both you added "<li>" + i + "<li>" instead of "<li>" + i + "</li>"
Missing slash small thing, but user agents are prepared to fix missing closing... and your code appeared with doubled li

Upvotes: 2

Related Questions