On dom ready, get all data-src from <img>'s and set them in the src attribute

10,072

Since 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.

Share:
10,072
jQuerybeast
Author by

jQuerybeast

A kid stepping an inch forward every day.

Updated on June 28, 2022

Comments

  • jQuerybeast
    jQuerybeast almost 2 years

    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>