only kyle
only kyle

Reputation: 13

How to add id to a innerhtml created by javascript

Here are the code:

const showsToTry = [
    './assets/cards/7.jpg',
    './assets/cards/8.jpg',
    './assets/cards/9.jpg',
    './assets/cards/10.jpg',
    './assets/cards/11.jpg',
    './assets/cards/12.jpg',
    ]


const showsToTrySection = document.querySelector('#shows-to-try')
showsToTry.forEach(song => {
    const showsToTrySongs = document.createElement('div')
    showsToTrySongs.className = 'card hp-subhero-card col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2'
    showsToTrySongs.innerHTML = `
 
   <img src="${song}" class="card-img-top pt-2 img-fluid" alt="...">
    <div class="card-body">
        <p class="hp-subhero-title">Purple Rain</p>
        <p class="hp-subhero-subtitle">Another song from my soul</p>
    </div>`
    showsToTrySection.appendChild(showsToTrySongs)
})

I want to add a unique id and a unique content for each picture in this array. How can I do it? Thank you very much

Upvotes: 0

Views: 58

Answers (1)

Arleigh Hix
Arleigh Hix

Reputation: 10877

You can use the array index in the loop as a distinct part of the id.

showsToTry.forEach((song, i) => {
  /* ... */
  showsToTrySongs.id = `song_${i}`
  /* ... */
}

That will give ids of "song_0" - "song_5"

const showsToTry = [
  './assets/cards/7.jpg',
  './assets/cards/8.jpg',
  './assets/cards/9.jpg',
  './assets/cards/10.jpg',
  './assets/cards/11.jpg',
  './assets/cards/12.jpg',
]


const showsToTrySection = document.querySelector('#shows-to-try')
showsToTry.forEach((song, i) => {
  const showsToTrySongs = document.createElement('div')
  showsToTrySongs.id = `song_${i}`
  showsToTrySongs.className = 'card hp-subhero-card col-12 col-sm-6 col-md-4 col-lg-3 col-xl-2'
  showsToTrySongs.innerHTML = `
 
   <img src="${song}" class="card-img-top pt-2 img-fluid" alt="...">
    <div class="card-body">
        <p class="hp-subhero-title">Purple Rain</p>
        <p class="hp-subhero-subtitle">Another song from my soul</p>
    </div>`
  showsToTrySection.appendChild(showsToTrySongs)
})
<div id="shows-to-try">

</div>

Upvotes: 2

Related Questions