0

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

1

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.