1

Right now I have a bunch of images stored in an array. I want those images to have ids of "left_slot", "middle_slot", and "right_slot". The following code works to give them those class names but not ids:

 function popArr() {
        $("#thumb_slider").children().each(function (index, element) {
            var newImg = $("<img />").attr({
                src: this.src,
                alt: 'space'
            }).addClass(index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot"));
            imgArr.push(newImg);
        });
        return imgArr;
    }

My question is, how would I change this function to give them ids depending on their index, instead of classes? I think the classes are getting mixed up with some other sections of code that I have elsewhere on the page. Thanks!

Digital Brent
  • 1,275
  • 7
  • 19
  • 47

3 Answers3

2

Use attr instead of addClass:

function popArr() {
    $("#thumb_slider").children().each(function (index, element) {
        var newImg = $("<img />").attr({
            src: this.src,
            alt: 'space',
            id: index == 0 ? "left_slot" : (index == 1 ? "middle_slot" : "right_slot")
        })
        imgArr.push(newImg);
    });
    return imgArr;
}
gabitzish
  • 9,535
  • 7
  • 44
  • 65
1

Check this out. So use the "id" attribute instead of the addClass function.

Community
  • 1
  • 1
the_red_baron
  • 868
  • 7
  • 14
0

Instead of .addClass(), use .prop( "id", ..... )

Alon Eitan
  • 11,997
  • 8
  • 49
  • 58