Home > Software engineering >  How can i dynamically add data- attribute to an array of html elements
How can i dynamically add data- attribute to an array of html elements

Time:01-30

I have a nodelist of html image elements which i converted to an array using the spread operator, so now i have an array of image elements like this [img.item, img.item, img.item, img.item, img.item, img.item]. This is what i want to do, i want to dynamically add a data attribute(data-id) to each element in the array depending on it's position in the array; so that the first element will have a data-id of 0, the seconnd element will have a data-id of 1, the third one will be 2 and the last will have a data-id of 5. here's the code

<div >
    <img src="https://image.shutterstock.com/image-photo/surreal-concept-roll-world-dice-260nw-1356798002.jpg" alt=""  >

    <img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA==&w=1000&q=80" alt=""  >

    <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt=""  >

    <img src="http://images2.fanpop.com/images/photos/5900000/Randomness-random-5997130-1280-800.jpg" alt=""  >

    <img src="https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8cmFuZG9tfGVufDB8fDB8fA==&w=1000&q=80" alt=""  >

    <img src="https://www.computerhope.com/jargon/r/random-dice.jpg" alt=""  >

</div>

<script> const images = document.querySelectorAll(".item")
    const imageArray = [...images] </script>

how do i go about it please?

CodePudding user response:

Use this:

imageArray.forEach(function(val, index){
    val.setAttribute('data-id', index);
});

CodePudding user response:

Iterate you image array and then you can set with the setAttribute function the data attribute. Like that:

const images = document.querySelectorAll(".item")

images.forEach((i, index) => {
  i.setAttribute('data-position', (index   1));
})


console.log(images[1])
img {
  width:200px;
}
<div >
    <img src="https://image.shutterstock.com/image-photo/surreal-concept-roll-world-dice-260nw-1356798002.jpg" alt=""  >

    <img src="https://images.unsplash.com/photo-1494253109108-2e30c049369b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8Mnx8cmFuZG9tJTIwZm9vZCUyMHN0b3JlfGVufDB8fDB8fA==&w=1000&q=80" alt=""  >

    <img src="https://www.thedesignwork.com/wp-content/uploads/2011/10/Random-Pictures-of-Conceptual-and-Creative-Ideas-02.jpg" alt=""  >

    <img src="http://images2.fanpop.com/images/photos/5900000/Randomness-random-5997130-1280-800.jpg" alt=""  >

    <img src="https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxzZWFyY2h8NXx8cmFuZG9tfGVufDB8fDB8fA==&w=1000&q=80" alt=""  >

    <img src="https://www.computerhope.com/jargon/r/random-dice.jpg" alt=""  >

</div>

  •  Tags:  
  • Related