Reputation: 9855
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'));
Upvotes: 0
Views: 49
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
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
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