In a page I have this:
<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>
and goes on.
I am trying to make an async load without using a jquery plugin and make it as simple as possible.
So I thought, when the dom is ready and the page is fully loaded, set the data-src to the src.
If I do this: console.log($('figure img').attr('data-src'))
I get only the first image. so it gives me result: img1.png
So how can I say, when dom ready all the figure > img > data-src to be set as src for that img.
So from this:
<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>
to this:
<figure><img src="img1.png"></figure>
<figure><img src="img2.png"></figure>
<figure><img src="img3.png"></figure>
<figure><img src="img4.png"></figure>
In a page I have this:
<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>
and goes on.
I am trying to make an async load without using a jquery plugin and make it as simple as possible.
So I thought, when the dom is ready and the page is fully loaded, set the data-src to the src.
If I do this: console.log($('figure img').attr('data-src'))
I get only the first image. so it gives me result: img1.png
So how can I say, when dom ready all the figure > img > data-src to be set as src for that img.
So from this:
<figure><img src="" data-src="img1.png"></figure>
<figure><img src="" data-src="img2.png"></figure>
<figure><img src="" data-src="img3.png"></figure>
<figure><img src="" data-src="img4.png"></figure>
to this:
<figure><img src="img1.png"></figure>
<figure><img src="img2.png"></figure>
<figure><img src="img3.png"></figure>
<figure><img src="img4.png"></figure>
Share
Improve this question
asked Feb 1, 2012 at 0:55
jQuerybeastjQuerybeast
14.5k39 gold badges119 silver badges198 bronze badges
2 Answers
Reset to default 12Since version 1.4.3 or so, jQuery has understood "data-" attributes directly. So just do this:
$('figure img').each(function() {
this.src = $(this).data('src');
});
You have to use .each()
in order to separate out the processing of each element in the initially-selected list so that the operation you perform can use that element by itself.
$('figure > img').prop('src',function() {
return $(this).attr('data-src');
});
Or a little quicker with getAttribute()
.
$('figure > img').prop('src',function() {
return this.getAttribute('data-src');
});
If you really want to remove the data-src
, then chain .removeAttr('data-src')
to the end.
$('figure > img').prop('src',function() {
return this.getAttribute('data-src');
}).removeAttr('data-src');