2

I need to store a bunch of Image SRC attribute values in an array. I want to search the DOM for all <img> tags and grab the SRC attribute for each and put it into an array.

I know I can create an array like: var imgSrc = new Array();

But how do I add each SRC attribute to the array?

0

2 Answers 2

1

The push method is how you add an item to an array in Javascript.

If you're using jQuery, this should get you what you're looking for:

var imgSrc = $("img").get().map(function(o, i) { 
    return $(o).attr("src"); 
});
Sign up to request clarification or add additional context in comments.

Comments

0
var imgSrc = [];
var imgEls = document.getElementsByTagName("img");
for(var i=0; i<imgEls.length; i++) {
    imgSrc.push(imgEls[i].getAttribute("src"));
}

... or, using jQuery:

var imgSrc = [];
$("img").each(function() {
    imgSrc.push($(this).attr("src"));
});

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.