** this is html **
In this html i have songList (song-container) in this i have songItem class which contain individual song info. in this i have songName class which show song name i want to change each song name but it doesn't change
let songItem = Array.from(document.querySelector(".songItem"));
let songs = [
{
Name: "love you zindagi",
filePath: "audio/song1.mp3",
coverPath: "covers/download.jpg",
},
{
Name: "zara-zara",
filePath: "audio/song5.mp3",
coverPath: "covers/download.jpg",
},
{
Name: "vaaste",
filePath: "audio/song8.mp3",
coverPath: "covers/download.jpg",
},
];
console.log(songs);
songItem.forEach((element, i) => {
console.log(element, i);
element.getElementsByClassName("songName")[0].innerText = songs[i].Name;
});
<div >
<h1>Best Song Collection</h1>
<div >
<span >
<img src="covers/download.jpg" />
</span>
<span >love you zindagi</span>
<span
><i onclick="songPlay ()"></i
></span>
<span
><i onclick="pauseSong ()"></i
></span>
</div>
<div >
<span >
<img src="covers/download.jpg" />
</span>
<span >love you zindagi</span>
<span ><i ></i></span>
</div>
<div >
<span >
<img src="covers/download.jpg" />
</span>
<span >love you zindagi</span>
<span ><i ></i></span>
</div>
</div>
CodePudding user response:
querySelector
returns the first element matching the selector. Use querySelectorAll
instead to get an iterable of all matched elements.
let songItem = Array.from(document.querySelectorAll(".songItem"));
let songs = [
{
Name: "love you zindagi",
filePath: "audio/song1.mp3",
coverPath: "covers/download.jpg",
},
{
Name: "zara-zara",
filePath: "audio/song5.mp3",
coverPath: "covers/download.jpg",
},
{
Name: "vaaste",
filePath: "audio/song8.mp3",
coverPath: "covers/download.jpg",
},
];
console.log(songs);
songItem.forEach((element, i) => {
console.log(element, i);
element.getElementsByClassName("songName")[0].innerText = songs[i].Name;
});
CodePudding user response:
As mentioned in the previous answers, this line
let songItem = Array.from(document.querySelector(".songItem"));
returns only the first element with class name "songItem"
. In order to return all of them you need to use querySelectorAll
. Also, you don't have to use Array.from()
. Therefore, you can use this line instead:
let songItem = document.querySelector(".songItem");
On the other hand, in the last line, using element.getElementsByClassName("songName")[0]
might not be the best practice, since "element" has only one child element with class name "songName", you can use querySelector in this case; like this:
element.querySelector(".songName").innerText = songs[i].Name;