wd950
wd950

Reputation: 1

Is there a way to give HTML elements unique IDs for using a for loop to create them in JavaScript?

I am creating several HTML buttons to act as a list and they are all added to the same which has id 'locations'. Is is possible to have different ids for each button.

Can I assign a variable to be the id rather than a string?

for(let i=0;(i<countryJSON.length)&&(i<10); i++){
    document.getElementById("locations").innerHTML += `<button type='button' id=countrylist class="list-group-item list-group-item-action">${countryJSON[i].name}</button>`;
}

Upvotes: 0

Views: 3079

Answers (3)

Alex Autem
Alex Autem

Reputation: 23

Sure, you're already using a template literal so you can set the id the same way you're setting the button text.

`<button id=${countryJSON[i].id}>${countryJSON[i].name}</button>`

Upvotes: 0

Amir
Amir

Reputation: 721

You can add the value of i in every button and it will be different since it changes each time for new button.

for(let i=0;(i<5)&&(i<10); i++){
    document.getElementById("locations").innerHTML += "<button type='button' id=countrylist-"+i+" class='list-group-item list-group-item-action'>test</button>";
    console.log('Button with id countrylist-'+i+' has been added.');
}
<div id="locations"></div>

Upvotes: 0

Arfeo
Arfeo

Reputation: 867

Did you mean sth like this?

const countryJSON = [
  { name: 'one' }, { name: 'two' }, { name: 'three' },
];

const locations = document.getElementById('locations');

for(let i = 0; i < countryJSON.length && i < 10; i++) {
  const btn = document.createElement('button');
  
  btn.id = `location${i}`;
  btn.className = 'list-group-item list-group-item-action';
  btn.innerHTML = countryJSON[i].name;
  
  locations.appendChild(btn);
}
<div id="locations"></div>

In this case every button has its own unique ID like location0, location1, etc.

Upvotes: 1

Related Questions