NickTr
NickTr

Reputation: 93

Loop through array, assign each value to an element attribute in Javascript / Jquery

I have an array: 'imageIds':

imageIds = ["778", "779", "780", "781", "782"];

I want to find all elements of class .preview-image on the page, of which I know the number will match the length of the array.

I then want to assign the first matching element a data attribute 'data-img-id' with the value of imageIds[0], the second matching element with imageIds[1] etc.

So the end result would be converting this:

<div class="preview-image">...</div>
<div class="preview-image">...</div>
<div class="preview-image">...</div> etc

in to this:

<div class="preview-image" data-img-id="778">...</div>
<div class="preview-image" data-img-id="779">...</div>
<div class="preview-image" data-img-id="780">...</div> etc

Not quite sure how to form the loop that would achieve this.

Upvotes: 7

Views: 2468

Answers (3)

ibrahim mahrir
ibrahim mahrir

Reputation: 31692

Select the elements then loop through them using each which passes the index of the current element to it's callback:

$(".preview-image").each(function(index) {
    $(this).attr("data-img-id", imageIds[index]);
});

Example:

var imageIds = [100, 200, 300];

$(".preview-image").each(function(index) {
  $(this).attr("data-img-id", imageIds[index]);
});
.preview-image::after {
  content: "data-img-id is: " attr(data-img-id);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="preview-image">...</div>
<div class="preview-image">...</div>
<div class="preview-image">...</div>

Upvotes: 5

Nina Scholz
Nina Scholz

Reputation: 386560

You could iterate the id array and assign the attribute to the same element of the class array with the same index.

var imageIds = ["778", "779", "780", "781", "782"],
    elements = document.getElementsByClassName('preview-image');

imageIds.forEach(function(id, i) {
    elements[i].setAttribute('data-img-id', id);
});

console.log(document.body.innerHTML);
<div class="preview-image"></div>
<div class="preview-image"></div>
<div class="preview-image"></div>
<div class="preview-image"></div>
<div class="preview-image"></div>

Upvotes: 3

caramba
caramba

Reputation: 22480

maybe something like this: I'm not sure how you "know" the number will match the array length. Either way, it's easy to change this around to go from the array.length and add the data attribute..

var imageIds = ["778", "779", "780", "781", "782"];

var elements = document.querySelectorAll('.preview-image');
for(var i=0; i < elements.length; i++) {

    elements[i].dataset.imgId = imageIds[i];

    console.log(elements[i].dataset);
}
<div class="preview-image">...</div>
<div class="preview-image">...</div>
<div class="preview-image">...</div>

Upvotes: 2

Related Questions