-2
<div class="e1">
<p><img alt="" src="/images/site/pr1.png" /></p>
</div>
<div class="e1">
<p><img alt="" src="/images/site/pr2.png" /></p>

</div>
<div class="e1">
<h1> My new h1 </h1>
</div>

How is it possibe to take the content of img src element of the first two div tag which class e1?

Piero G
  • 1
  • 1
  • document.getElementsByClassName("e1") – Piero G Sep 09 '15 at 05:36
  • possible duplicate of [Get all Attributes from a HTML element with Javascript/jQuery](http://stackoverflow.com/questions/2048720/get-all-attributes-from-a-html-element-with-javascript-jquery) – Clarkie Sep 09 '15 at 05:55

1 Answers1

3

Simply use the querySelectorAll method on document. You can then map the returned NodeList to an array of src attributes.

var images = document.querySelectorAll('.e1 img[src]'),
    sources = Array.prototype.map.call(images, function(img) {
        return img.src;
    });

I've used the above selector '.e1 img[src]' to make sure that the returned NodeList only has images with src attributes.

JSFiddle Demo ~ http://jsfiddle.net/u9Lkada3/1/


Don't forget! You need to run the script after the elements exist in the document. The easiest way to ensure this is to put your script at the end, just before the closing </body> tag.

Phil
  • 157,677
  • 23
  • 242
  • 245
  • 2
    @PieroG seems to work just fine in the fiddle. Your HTML must be different or you're running the JavaScript **before** the elements exist in the document. – Phil Sep 09 '15 at 05:45