Shadow_boi
Shadow_boi

Reputation: 2198

How to get background image of the first div with a specified class using jquery?

How do I get the first "grid_5" class div background image url? (eg: test1.jpg in the following example)

<div>
<div class="grid_5" style="background: url("test1.jpg");">
<div class="grid_5" style="background: url("test2.jpg");">
<div class="grid_5" style="background: url("test3.jpg");">
</div>

I tried the following but it doesnt work:

$('.grid_5:first').attr('background')
$('.grid_5')[0].attr('background')

Please tell me why is that and what should be the correct code for it.

Upvotes: 0

Views: 792

Answers (4)

mcgrailm
mcgrailm

Reputation: 17638

I like this style

 $('.grid_5:first').css('background')

Upvotes: 0

Mike Lewis
Mike Lewis

Reputation: 64167

If you change the style attribute to background-image, it should work just fine, as seen here:

http://jsfiddle.net/KKRTz/

<div>
<div class="grid_5" style="background-image: url('test1.jpg');">
<div class="grid_5" style="background-image: url('test2.jpg');">
<div class="grid_5" style="background-image: url('test3.jpg');">
</div>

$('.grid_5').first().css('background-image');

Upvotes: 0

moe
moe

Reputation: 29744

$('.grid_5:eq(0)').css('background');

Upvotes: 2

Liza Daly
Liza Daly

Reputation: 2963

You want .css('background').

Upvotes: 0

Related Questions