How to insert text in a li with an array?

时间:2016-07-11 20:30:05

标签: javascript html arrays

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?

3 个答案:

答案 0 :(得分:3)

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>

答案 1 :(得分:1)

In case you dont want to hard-code your <li> elements you can create them dynamically. You can also use map():

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

a.map(function (el) {
  var li = document.createElement("li");
  li.appendChild(document.createTextNode(el));
  document.getElementById("list").appendChild(li)
});
<ul id="list">
</ul>

Side Note:

<li> elements should have a closing tag

答案 2 :(得分:1)

Soemthing like this in pure JavaScript:

var arr = [1, 2, 3, 4];
var list = document.getElementById('list');
for (var i = 0; i < arr.length; ++i) {
  var item = document.createElement('li');
  var text = document.createTextNode(arr[i]);
  item.appendChild(text);
  list.appendChild(item);
}
<ul id="list"></ul>