user115203
user115203

Reputation: 17

How can I get the src attributes of each image element with the same class in JQuery?

How can I get the src attributes of each image element with the same class and store it in an array to access it in JQuery?

Here is the html

<div id="preload">
  <img class="pre-img" src="images/img1.jpg">
  <img class="pre-img" src="images/img2.jpg">
  <img class="pre-img" src="images/img3.jpg">
</div>

and here is the jquery code

function preloadImages(){
    var image = $(".pre-img").toArray();
    for(var i=0; i < image.length; i++)
    {
        var path = image[i].attr('src');
        console.log(path);
    }
}

Can someone tell me where I'm doing this wrong?

Upvotes: 0

Views: 57

Answers (2)

Tay
Tay

Reputation: 300

function preloadImages(){
debugger;
    var image = $(".pre-img").toArray();
    for(var i=0; i < image.length; i++)
    {
        var path = image[i].src; // or may be this, $(image[i]).attr('src');
        console.log(path);
    }
}

preloadImages();

Note: You need a wrapper to access attr() method.

Upvotes: 1

tymeJV
tymeJV

Reputation: 104775

You can use jQuerys map function:

var imagePaths = $(".pre-img").map(function() {
    return this.src; //this refers to the DOM element, so you can simply access the property you want
}).get(); //.get() to convert the result to an array

Upvotes: 1

Related Questions