user1318194
user1318194

Reputation:

Using jQuery `.attr()` outside the scope of a `.each()` - possible?

I want to change the first element with class .viewer's src attribute to the value of it's data-src attribute. The obvious code doesn't work:

$(".viewer").first().show().attr('src', $(this).attr('data-src'));

From reading other question on SO, I find you have to do this:

$(".viewer").first().show().each(function(){
    $(this).attr('src', $(this).attr('data-src'));
});

It does work, and I do understand why (this doesn't refer to the element outside of the scope of the .each) - but it seems very weird to run .each() after you've already used .first().

Is there a cleaner way to write the above code?

Upvotes: 1

Views: 93

Answers (2)

adeneo
adeneo

Reputation: 318182

You can always just use a variable:

var elem = $(".viewer").first();
    elem.show().attr('src', elem.attr('data-src'));

Upvotes: 2

Quentin
Quentin

Reputation: 943510

Store data you want to reuse in a variable.

var viewer = $(".viewer").first().show();
viewer.attr('src', viewer.data('src'));

Upvotes: 3

Related Questions