Blind Blind - 4 months ago 10
HTML Question

How to insert text in a li with an array?

I'm creating a site with many list and I have a structure like this:



<ul class="list-container">
<li>TEXT
<li>TEXT
<li>TEXT
</ul>





Can I create an array like
var a = [1,2,3,4]
and
li
becomes:



<ul>
<li>1
<li>2
<li>3
<li>4
</ul>





I tried with:



var a = [
"Testo 1",
"Testo 2",
"Testo 3",
"Testo 4"
];

for(var i = 0;i < document.querySelector("li").length;i++)
{
document.querySelector("li")[i].innerHTML = a[i];
}

<ul>
<li>
<li>
<li>
</ul>





It doesn't work, Anyone can help me?

Answer

The querySelector() method only returns the first element that matches the specified selectors. To return all the matches, use the querySelectorAll() method instead.

var a = [
  "Testo 1",
  "Testo 2",
  "Testo 3",
  "Testo 4"
];
for (var i = 0; i < document.querySelectorAll("li").length; i++) {
  document.querySelectorAll("li")[i].innerHTML = a[i];
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<ul>
  <li>
  <li>
  <li>
</ul>