views:

38

answers:

3

Is it possible to use jQuery to check if #page has got a background image - #page could look like this:

<div id="page" style="background-image: url(xxx)"></div>

if it contains a background image, it should add a class to #page

+1  A: 

You can try this:

if ($('#page').attr('style').indexOf('image') !== -1){
  alert('It has the background image');
}

Or use the css method:

if ($('#page').css('background-image')){
  alert('It has the background image');
}
Sarfraz
A: 
var image = $('#page').css('background-image');

Should do the job.

pharalia
A: 

You can check the value using .css(), then add the class using addClass():

var $p = $("#page");
if ($p.css("background-image"))
    $p.addClass("bg");

Or (requires jQuery 1.4):

$("#page").addClass(function () {
    return $(this).css("background-image") ? "bg" : "";        
});

Try an example out here.

Andy E
The problem is that it will always have style="background-image()"If there no background image, the src of it will just be empty
Nicky Christensen