Menor
Menor

Reputation: 300

How to assign a different id for every element

I have got two list, one contains text for span elements, that I assign using this forEach loop:

spans.forEach(function(el) {
  const span = document.createElement('span');
  span.innerHTML = el;
  list.appendChild(span);
})

How would I assign an id to every span in the list using another list? Both lists contains the same amount of elements and the id[0] should be assign to text[0] and so on.

Upvotes: 1

Views: 358

Answers (2)

Beingnin
Beingnin

Reputation: 2422

Assuming your seconds list is named as ids

spans.forEach(function(el,index) {
  const span = document.createElement('span');
  span.innerHTML = el;
  span.id=ids[index];
  list.appendChild(span);    
})

Upvotes: 1

Luís Ramalho
Luís Ramalho

Reputation: 10208

You could do it by using the second parameter of forEach, like so:

let spans = ['one', 'two', 'three'];
let list = document.getElementById("list");

spans.forEach(function(el, i) {
  const span = document.createElement("span");
  span.innerHTML = el;
  span.id = spans[i];
  list.appendChild(span);
});

for (let child of list.childNodes) {
  console.log(child);
}
<div id="list"></div>

Upvotes: 3

Related Questions