Rajarshi
Rajarshi

Reputation: 2509

jquery: Getting 'src' from data-url and add the same

I'm new to JavaScript, jQuery and Stack.

I'm trying to get the url with data().url and add the same as src to each img. Here is an example of the HTML.

<ol>
  <li><div class="image"><img data-url="https://lh4.googleusercontent.com/.../s400/image-1.png"/></div></li>
  <li><div class="image"><img data-url="https://lh4.googleusercontent.com/.../s400/image-2.png"/></div></li>
  <li><div class="image"><img data-url="https://lh4.googleusercontent.com/.../s400/image-3.png"/></div></li>
</ol>

How this can be achieved with jquery?

Upvotes: 0

Views: 1229

Answers (4)

Ivan Chernykh
Ivan Chernykh

Reputation: 42166

Try this:

$(".image img").each(function(){
    $(this).attr("src" , $(this).data().url );
});

Here is the example: http://jsfiddle.net/42A93/1/

Welcome to SO!

Upvotes: 1

OctoD
OctoD

Reputation: 361

$( '.image img' ).map( function(){
     this.setAttribute('src', this.getAttribute('data-url'));
});

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$(".image img").attr('src', function(){
    return $(this).data('url');
})

Upvotes: 0

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382150

You could do this :

$('.image img').attr('src', function(){ return $(this).data('url') });

Upvotes: 1

Related Questions