Skip to content Skip to sidebar Skip to footer

How To Assign Identifiers To All Html Elements Of A Particular Type?

My site embeds posts from an RSS feed, and some of these posts contain

Solution 1:

This is a for loop solution.

let audio = document.querySelectorAll('audio');

for (let i = 0; i < audio.length; i++) {
  audio[i].setAttribute('id', i);
  console.log(audio[i]);
}
<audiosrc="1.mp3"></audio><audiosrc="2.mp3"></audio><audiosrc="3.mp3"></audio>

Solution 2:

Is this what you're looking for? Using jQuery: JSFiddle

for (var a = 0; a < $('audio').length; a++) { //Loops every audio element
   $('audio').eq(a).attr('id', "audioNum" + a); //Adds ID from loop index
}

Solution 3:

I would do something like this:

const matches = document.querySelectorAll("audio");

With this method, we are storing in a constant named matches all the elements in the DOM that have the tag .

Then you can probably add the ID, as a unique identifier:

const matches = document.querySelectorAll("audio");

matches.forEach((match, i) => match.id = i);

In the example, I am adding as ID property the iteration number (from 0 to X) for every audio element in the DOM.

This is the output:

output of const matches

So now you have an array of every audio element in the DOM with a unique identifier ready to be used

Post a Comment for "How To Assign Identifiers To All Html Elements Of A Particular Type?"