Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Jquery .addClass on html elements in array

I have a few html image tags that fill an array. On the page - http://www.digitalbrent.com/lab - three of the elements in the array are displayed. I need to add a class to them after a button is clicked. The class is different for each if the imgs being displayed from the array. Here's the code:

$(document).ready(function(){        //populates array with images

    var shipImgs = $("#thumb_slider").children();
    console.log(shipImgs);

    $.each(shipImgs,function(i,elem){
        var tag = "<img src='" + $(elem).attr('src') + "' alt='space'/>"; // This is how I made the image tags.
        imgArr.push(tag);
    });
    console.log(imgArr);

});

$("#basic_ul").html(imgArr[b] + imgArr[a] + imgArr[c]); //displays the images
        imgArr[b].addClass("left_slot");
        imgArr[a].addClass("middle_slot");
        imgArr[c].addClass("right_slot");

I've also tried it with the selector around the array items, $(imgArr[b]).addClass("left_slot"); but that didn't work either.

Any advice at all would be greatly appreciated. I've looked through similar questions here on stackoverflow but no luck. I've been researching this project for a while now and can't find anything.

like image 795
Digital Brent Avatar asked Jun 19 '26 20:06

Digital Brent


2 Answers

Your imgArr only holds an array of strings of the image tags' HTML.

Instead, if you pass that string to the jQuery function, you will get an in-memory node that you can then add to the document.

Try changing your code above to:

$(document).ready(function(){        //populates array with images
    var $basicUl = $('#basic_ul'); // cache the selector
    var shipImgs = $("#thumb_slider").children().each(function(index, element) {
        var newImg = $("<img />").attr({src: this.src, alt: 'space'}).addClass(index == 0 ? "middle_slot" : (index == 1 ? "left_slot" : "right_slot"));
        $basicUl.append(newImg);
    });
});
like image 112
GregL Avatar answered Jun 22 '26 11:06

GregL


You should be using each() to iterate jQuery collections, and not $.each().

shipImgs.each(function () {
    var img = "<img src='" + $(this).attr('src') + "' alt='space'/>";
    imgArr.push(img);
});
like image 29
elclanrs Avatar answered Jun 22 '26 11:06

elclanrs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!