Loop through array, assign each attribute an element attribute in Javascript / JQuery

I have an array: 'imageIds':

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

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

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

So, the end result will convert this:

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

in that:

<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 a cycle that will achieve this.

+4
source share
3 answers

Select the items, then scroll through them using each, which passes the index of the current item to the 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>
Run codeHide result
+2

id .

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>
Hide result
+3

maybe something like this: I'm not sure how you “know” the number will correspond to the length of the array. In any case, it's easy to change this to go from array.length and add a 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>
Run codeHide result
+2
source

Source: https://habr.com/ru/post/1678961/


All Articles