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}" alt="...">
<div >
<p >Purple Rain</p>
<p >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
CodePudding user response:
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}" alt="...">
<div >
<p >Purple Rain</p>
<p >Another song from my soul</p>
</div>`
showsToTrySection.appendChild(showsToTrySongs)
})
<div id="shows-to-try">
</div>