2

I have many divs with id="imgLinks"

<div><img  id="imgLinks" u=image src="../../../../images/1.jpg" /></div>
<div><img  id="imgLinks" u=image src="../../../../images/3.jpg" /></div>
<div><img  id="imgLinks" u=image src="../../../../images/5.jpg" /></div>

I need on button click put all src to array

$(document).on('click', '#navigation #Download', function() {
    var imgLinks = [];
    $("#imgLinks").each(function() {
        var name = $(this).attr("src");
        imgLinks.push(name);
    });
});

But this code put only first source, how to put all of them?

3
  • Move var imgLinks = [] outside of the click handler. You're redefining it every time you click an image Aug 4, 2015 at 13:16
  • 6
    ids should be unique per element in a single page. invalid markup. change to class='imgLinks' instead and change your selector to class selector then.
    – Jai
    Aug 4, 2015 at 13:16
  • If you have no control over the HTML, you could use $("[id='imgLinks']") instead, but I highly suggest you follow what @Jai said.
    – Stryner
    Aug 4, 2015 at 13:20

2 Answers 2

4

change id attribute to class because same ids in a single page not allowed/ produces invalid markup.

$(document).on('click', '#navigation #Download', function() {
    var imgLinks = $(".imgLinks").map(function() {
            return $(this).attr("src");
        }).get();
    console.log(imgLinks); // [array]
});

.map().get() lets you create an array while returning the src of every .imgLink in each iteration.

0
1

Even though having same ID for different elements seems to make any difference, having Unique IDs are the standard way. You can either change the ID to class and then select using the class name or utilize the attribute you have used

$(document).on('click', '#navigation #Download', function() {
    var imgLinks = [];
    $('img[u=image]').each(function() {
        var name = $(this).attr("src");
        imgLinks.push(name);
    });
});

Edit to improve answer based on accepted answer.

$(document).on('click', '#navigation #Download', function() {
    var imgLinks = $('img[u=image]').map(function() {
            return $(this).attr("src");
        }).get();
});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.