Liam
Liam

Reputation: 9855

Change image source for all images with jQuery

I have some empty image tags on my page with an image stored in a data attribute.

On page load i'd like to take this value from the data attribute and place it in the source...

$('div').each('img').attr('src', $(this).data('src'));

http://jsfiddle.net/09e9bdwd/

Upvotes: 0

Views: 49

Answers (3)

Carl Edwards
Carl Edwards

Reputation: 14434

A slightly speedier approach vs. using .each()

var images     = document.querySelectorAll("div img"),
    imageCount = document.images.length;

for (var i = 0; i < imageCount; i++) {
  images[i].setAttribute("src", images[i].dataset.src);
}
<div>
  <img src="" data-src="http://placehold.it/150x150">
</div>

<div>
  <img src="" data-src="http://placehold.it/150x150">
</div>

<div>
  <img src="" data-src="http://placehold.it/150x150">
</div>

Upvotes: 0

Claudio Redi
Claudio Redi

Reputation: 68400

You're not using each correctly. Here you have a usage sample

$('div img').each(function() {
   var $this = $(this);
   $this.attr('src', $this.data('src'));
})

Upvotes: 4

lmgonzalves
lmgonzalves

Reputation: 6588

This is the correct way to do that:

$('div img').each(function(){
    $(this).attr('src', $(this).data('src'));    
});

DEMO: https://jsfiddle.net/lmgonzalves/09e9bdwd/1/

Upvotes: 1

Related Questions