如何在JavaScript中使用innerHTML为创建的元素分配一个ID?

huangapple go评论73阅读模式
英文:

how To give an ID to an element created with innerHTML in javascript?

问题

I created a parent div in html and created an array of objects that contains infos about the child Divs, and because there is a lot of songs I can't create all of theme in HTML, what I want is when I click a song the infos in the object get added to the player what I'm thinking of is some how create a loop that gives IDs to each objects of the songs so that I can create I loop that get's the ID of the clicked elements and get the right infos.

This is my Code :

<div class="playlist-songs" id="addTo"></div>
<div class="song-p-now">
  <div class="song-poster"><img src="img/7.jpg" alt=""></div>
  <div class="song-artist-name">
    <div class="song-name">Me, Myself & I</div>
    <div class="artist-name">G-easy</div>
  </div>
</div>
const playlistSongs = document.querySelector(".playlist-songs");
const btns = document.querySelectorAll('.song-details');
const playingNow = document.querySelector('.song-p-now');

const goodVibesPlaylist = [{
    img: 'img/2.jpg',
    idd: 1,
    songName: 'Am I Wrong',
    audio: new Audio('audio/Am-I-wrong.mp3'),
    artist: 'Nico & Vinz',
  },
  // Other songs in the playlist...
]

// That's How I add the songs 
let songsHTML = '';

for (let song of goodVibesPlaylist) {
  const html = `
    <div class="song-details" id="${song.idd}">
      <div class="song-num">${song.idd}</div>
      <div class="song-poster"><img src=${song.img} alt=""></div>
      <div class="song-artist-name">
          <div class="song-name">${song.songName}</div>
          <div class="artist-name">${song.artist}</div>
      </div>
      <div class="play-btn"><span class="material-symbols-outlined">play_arrow</span></div>
    </div>`;
  songsHTML += html;
}

document.querySelector('#addTo').innerHTML = songsHTML;

// This is the eventListener loop
for (let song of btns) {
  playingNow.innerHTML = `
    <div class="song-poster"><img src="img/7.jpg" alt=""></div>
    <div class="song-artist-name">
        <div class="song-name">Me, Myself & I</div>
        <div class="artist-name">G-easy</div>
    </div>`;
}

I hope this helps with your code!

英文:

I created a parent div in html and created an array of objects that contains infos about the child Divs, and because there is a lot of songs I can't create all of theme in HTML, what I want is when I click a song the infos in the object get added to the player what I'm thinking of is some how create a loop that gives IDs to each objects of the songs so that I can create I loop that get's the ID of the clicked elements and get the right infos.

This is my Code :

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const playlistSongs = document.querySelector(&quot;.playlist-songs&quot;);
const btns = document.querySelector(&#39;.song-details&#39;);
const playingNow = document.querySelector(&#39;.song-p-now&#39;);

const goodVibesPlaylist = [{
    img: &#39;img/2.jpg&#39;,
    idd: 1,
    songName: &#39;Am I Wrong&#39;,
    audio: new Audio(&#39;audio/Am-I-wrong.mp3&#39;),
    artist: &#39;Nico &amp; Vinz&#39;,
  },
  {
    img: &#39;img/3.jpg&#39;,
    idd: 2,
    songName: &#39;Sex,Drugs,Etc&#39;,
    audio: new Audio(&#39;audio/Sex-Drugs-Etc.mp3&#39;),
    artist: &#39;Beach Weather&#39;,

  },


  {
    img: &#39;img/7.jpg&#39;,
    idd: 3,
    songName: &#39;Me Myself &amp; I &#39;,
    audio: new Audio(&#39;audio/Me-Myself-I.mp3&#39;),
    artist: &#39;G-easy&#39;,

  },

  {
    img: &#39;img/4.jpg&#39;,
    idd: 4,
    songName: &#39;Blood In The Water&#39;,
    audio: new Audio(&#39;audio/Blood-In-The-Water.mp3&#39;),
    artist: &#39;grandson&#39;,
  },

  {
    img: &#39;img/5.jpg&#39;,
    idd: 5,
    songName: &#39;Eastside&#39;,
    audio: new Audio(&#39;audio/Eastside.mp3&#39;),
    artist: &#39;Benny Blanco&#39;,
  },

  {
    img: &#39;img/6.jpg&#39;,
    idd: 6,
    songName: &#39;Everything Black &#39;,
    audio: new Audio(&#39;audio/Everything-Black.mp3&#39;),
    artist: &#39;Unlike Puto&#39;,

  }
]

// That&#39;s How I add the songs 

let songsHTML = &#39;&#39;;

const elemt = document.createAttribute

for (let song of goodVibesPlaylist) {
  const html = `
   &lt;div class=&quot;song-details&quot; id=&quot;${song.idd}&quot;&gt; //here how I tried to give IDs
    &lt;div class=&quot;song-num &quot; &gt;${song.idd}&lt;/div&gt;
    &lt;div class=&quot;song-poster&quot;&gt;&lt;img src=${song.img} alt=&quot;&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;song-artist-name&quot;&gt;
        &lt;div class=&quot;song-name&quot;&gt;${song.songName}&lt;/div&gt;
        &lt;div class=&quot;artist-name&quot;&gt;N${song.artist}&lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;play-btn&quot;&gt;&lt;span class=&quot;material-symbols-outlined&quot;&gt;
        play_arrow
        &lt;/span&gt;
    &lt;/div&gt;
    &lt;/div&gt;`;

  songsHTML += html;
  console.log(btns.id)
}

document.querySelector(&#39;#addTo&#39;)
  .innerHTML = songsHTML;


// This is the eventListnner loop


for (let song of btns) {

  playingNow.innerHTML = ` &lt;div class=&quot;song-poster&quot;&gt;&lt;img src=&quot;img/7.jpg&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;song-artist-name&quot;&gt;
    &lt;div class=&quot;song-name&quot;&gt;Me,Myself &amp; I&lt;/div&gt;
    &lt;div class=&quot;artist-name&quot;&gt;G-easy&lt;/div&gt;
&lt;/div&gt;`

}

<!-- language: lang-html -->

&lt;div class=&quot;playlist-songs&quot; id=&quot;addTo&quot;&gt;&lt;/div&gt;

&lt;div class=&quot;song-p-now&quot;&gt;
  &lt;div class=&quot;song-poster&quot;&gt;&lt;img src=&quot;img/7.jpg&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
  &lt;div class=&quot;song-artist-name&quot;&gt;
    &lt;div class=&quot;song-name&quot;&gt;Me,Myself &amp; I&lt;/div&gt;
    &lt;div class=&quot;artist-name&quot;&gt;G-easy&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

答案1

得分: 0

当你通过const btns = document.querySelector('.song-details');选择div时,此时不存在具有类名“song-details”的div元素。你正在尝试在元素创建之前选择它。我认为这可能会解决这个问题。

window.onload = function(){
  const btns = document.querySelector('.song-details');
}

了解更多关于onload事件的信息,请访问https://www.w3schools.com/jsref/event_onload.asp。

英文:

When you are selecting the div by const btns = document.querySelector(&#39;.song-details&#39;);. At that point. No div with class "song-details" exists. What you are doing is you selecting an element before it is even created. I believe this might fix the issue.

window.onload = function(){
  const btns = document.querySelector(&#39;.song-details&#39;);
}

https://www.w3schools.com/jsref/event_onload.asp&lt;br>
Read more about onload event here

答案2

得分: 0

你可以使用<template>元素更好地组织你的代码。

<template id="songTemplate">
  <div class="song-details"> IDs
    <div class="song-num"></div>
    <div class="song-poster"><img alt=""></div>
    <div class="song-artist-name">
      <div class="song-name"></div>
      <div class="artist-name"></div>
    </div>
    <div class="play-btn"><span class="material-symbols-outlined">
      play_arrow
      </span>
    </div>
  </div>
</template>

然后,你可以通过查询选择器轻松访问所有这些元素。

const template = document.getElementById("songTemplate");
for (let song of goodVibesPlaylist) {
  const content = template.content.cloneNode(true);
  content.querySelector('.song-details').id = song.idd;
  content.querySelector('.song-num').textContent = song.idd;
  content.querySelector('.song-poster > img').src = song.img;
  content.querySelector('.song-name').textContent = song.songName;
  content.querySelector('.artist-name').textContent = 'N' + song.artist;
  console.log(content.firstElementChild.id);
  document.querySelector('#addTo').append(content);
}
英文:

You can use a &lt;template&gt; element to organize your code better.

&lt;template id=&quot;songTemplate&quot;&gt;
  &lt;div class=&quot;song-details&quot;&gt; IDs
    &lt;div class=&quot;song-num&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;song-poster&quot;&gt;&lt;img alt=&quot;&quot;&gt;&lt;/div&gt;
    &lt;div class=&quot;song-artist-name&quot;&gt;
      &lt;div class=&quot;song-name&quot;&gt;&lt;/div&gt;
      &lt;div class=&quot;artist-name&quot;&gt;&lt;/div&gt;
    &lt;/div&gt;
    &lt;div class=&quot;play-btn&quot;&gt;&lt;span class=&quot;material-symbols-outlined&quot;&gt;
      play_arrow
      &lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;
&lt;/template&gt;

Then, you can easily access all the elements through query selectors.

const template = document.getElementById(&quot;songTemplate&quot;);
for (let song of goodVibesPlaylist) {
  const content = template.content.cloneNode(true);
  content.querySelector(&#39;.song-details&#39;).id = song.idd;
  content.querySelector(&#39;.song-num&#39;).textContent = song.idd;
  content.querySelector(&#39;.song-poster &gt; img&#39;).src = song.img;
  content.querySelector(&#39;.song-name&#39;).textContent = song.songName;
  content.querySelector(&#39;.artist-name&#39;).textContent = &#39;N&#39; + song.artist;
  console.log(content.firstElementChild.id);
  document.querySelector(&#39;#addTo&#39;).append(content);
}

答案3

得分: 0

以下是您要翻译的代码部分:

const goodVibesPlaylist = [{
    img: 'img/2.jpg',
    idd: 1,
    songName: 'Am I Wrong',
    audio: new Audio('audio/Am-I-wrong.mp3'),
    artist: 'Nico & Vinz',
  },
  {
    img: 'img/3.jpg',
    idd: 2,
    songName: 'Sex,Drugs,Etc',
    audio: new Audio('audio/Sex-Drugs-Etc.mp3'),
    artist: 'Beach Weather',
  },
  {
    img: 'img/7.jpg',
    idd: 3,
    songName: 'Me Myself & I ',
    audio: new Audio('audio/Me-Myself-I.mp3'),
    artist: 'G-easy',
  },
  {
    img: 'img/4.jpg',
    idd: 4,
    songName: 'Blood In The Water',
    audio: new Audio('audio/Blood-In-The-Water.mp3'),
    artist: 'grandson',
  },
  {
    img: 'img/5.jpg',
    idd: 5,
    songName: 'Eastside',
    audio: new Audio('audio/Eastside.mp3'),
    artist: 'Benny Blanco',
  },
  {
    img: 'img/6.jpg',
    idd: 6,
    songName: 'Everything Black ',
    audio: new Audio('audio/Everything-Black.mp3'),
    artist: 'Unlike Puto',
  }
]

// 这是我添加歌曲的方式

let songsHTML = '';

const elemt = document.createAttribute;

// 这是创建这些元素的循环
// 在此循环后放置元素
for (let song of goodVibesPlaylist) {
  const html = `
   <div class="song-details" id="${song.idd}"> 
    <div class="song-num ">${song.idd}</div>
    <div class="song-poster"><img src=${song.img} alt=""></div>
    <div class="song-artist-name">
        <div class="song-name">${song.songName}</div>
        <div class="artist-name">${song.artist}</div>
    </div>
    <div class="play-btn"><span class="material-symbols-outlined">
        play_arrow
        </span>
    </div>
    </div>`;

  songsHTML += html;
}

document.querySelector('#addTo')
  .innerHTML = songsHTML;

// 这是事件监听器循环

// 在此位置,这些元素已经创建,您现在可以访问它们
const playlistSongs = document.querySelectorAll(".playlist-songs");
const btns = document.querySelectorAll('.song-details');
const playingNow = document.querySelectorAll('.song-p-now');

for (let song of btns) {
  playingNow.innerHTML = `<div class="song-poster"><img src="img/7.jpg" alt=""></div>
  <div class="song-artist-name">
      <div class="song-name">Me,Myself & I</div>
      <div class="artist-name">G-easy</div>
  </div>`;
}

请注意,我已经将代码中的注释保留在翻译中,以确保代码的完整性。如果需要进一步的帮助,请告诉我。

英文:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const goodVibesPlaylist = [{
img: &#39;img/2.jpg&#39;,
idd: 1,
songName: &#39;Am I Wrong&#39;,
audio: new Audio(&#39;audio/Am-I-wrong.mp3&#39;),
artist: &#39;Nico &amp; Vinz&#39;,
},
{
img: &#39;img/3.jpg&#39;,
idd: 2,
songName: &#39;Sex,Drugs,Etc&#39;,
audio: new Audio(&#39;audio/Sex-Drugs-Etc.mp3&#39;),
artist: &#39;Beach Weather&#39;,
},
{
img: &#39;img/7.jpg&#39;,
idd: 3,
songName: &#39;Me Myself &amp; I &#39;,
audio: new Audio(&#39;audio/Me-Myself-I.mp3&#39;),
artist: &#39;G-easy&#39;,
},
{
img: &#39;img/4.jpg&#39;,
idd: 4,
songName: &#39;Blood In The Water&#39;,
audio: new Audio(&#39;audio/Blood-In-The-Water.mp3&#39;),
artist: &#39;grandson&#39;,
},
{
img: &#39;img/5.jpg&#39;,
idd: 5,
songName: &#39;Eastside&#39;,
audio: new Audio(&#39;audio/Eastside.mp3&#39;),
artist: &#39;Benny Blanco&#39;,
},
{
img: &#39;img/6.jpg&#39;,
idd: 6,
songName: &#39;Everything Black &#39;,
audio: new Audio(&#39;audio/Everything-Black.mp3&#39;),
artist: &#39;Unlike Puto&#39;,
}
]
// That&#39;s How I add the songs 
let songsHTML = &#39;&#39;;
const elemt = document.createAttribute
// this is the loop that creates those elements 
// put the elements after this loop
for (let song of goodVibesPlaylist) {
const html = `
&lt;div class=&quot;song-details&quot; id=&quot;${song.idd}&quot;&gt; 
&lt;div class=&quot;song-num &quot; &gt;${song.idd}&lt;/div&gt;
&lt;div class=&quot;song-poster&quot;&gt;&lt;img src=${song.img} alt=&quot;&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;song-artist-name&quot;&gt;
&lt;div class=&quot;song-name&quot;&gt;${song.songName}&lt;/div&gt;
&lt;div class=&quot;artist-name&quot;&gt;N${song.artist}&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;play-btn&quot;&gt;&lt;span class=&quot;material-symbols-outlined&quot;&gt;
play_arrow
&lt;/span&gt;
&lt;/div&gt;
&lt;/div&gt;`;
songsHTML += html;
}
document.querySelector(&#39;#addTo&#39;)
.innerHTML = songsHTML;
// This is the eventListnner loop
// at this posint these elements have been created , you can access them now
const playlistSongs = document.querySelectorAll(&quot;.playlist-songs&quot;);
const btns = document.querySelectorAll(&#39;.song-details&#39;);
const playingNow = document.querySelectorAll(&#39;.song-p-now&#39;);
for (let song of btns) {
playingNow.innerHTML = ` &lt;div class=&quot;song-poster&quot;&gt;&lt;img src=&quot;img/7.jpg&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;song-artist-name&quot;&gt;
&lt;div class=&quot;song-name&quot;&gt;Me,Myself &amp; I&lt;/div&gt;
&lt;div class=&quot;artist-name&quot;&gt;G-easy&lt;/div&gt;
&lt;/div&gt;`
}

<!-- language: lang-html -->

  &lt;div class=&quot;song-p-now&quot;&gt;
&lt;div class=&quot;song-poster&quot;&gt;&lt;img src=&quot;img/7.jpg&quot; alt=&quot;&quot;&gt;&lt;/div&gt;
&lt;div class=&quot;song-artist-name&quot;&gt;
&lt;div class=&quot;song-name&quot;&gt;Me,Myself &amp; I&lt;/div&gt;
&lt;div class=&quot;artist-name&quot;&gt;G-easy&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;

<!-- end snippet -->

your code is fine,

the problem is you are trying to access these elements before they are created,

const playlistSongs = document.querySelector(&quot;.playlist-songs&quot;);
const btns = document.querySelector(&#39;.song-details&#39;);
const playingNow = document.querySelector(&#39;.song-p-now&#39;);

open your devtools and console log btns
you will see its null, this is becase when you call document.getElementById or document.querySelector for an element that does not exist, you will get null,

so in your code when you said console.log(btns.id) you are basicly saying console.log(null.id) this will throw an error bacause the null object does not have an id value

solution

const playlistSongs = document.querySelector(&quot;.playlist-songs&quot;);
const btns = document.querySelector(&#39;.song-details&#39;);
const playingNow = document.querySelector(&#39;.song-p-now&#39;);

put these elements after the for loop that creates them, and use querySelectorAll not querySelector, querySelector will just get the first element it finds with that class

i have made the canges, see the comments in the code

huangapple
  • 本文由 发表于 2023年5月14日 05:09:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76244886.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定