7

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

2 Answers 2

22

The default value for background-image is "none". So you can do it like this:

if ($('#page').css('background-image') != 'none') {
  alert('There is a background image');
}
Sign up to request clarification or add additional context in comments.

1 Comment

In case anyone's wondering, this answer works as written even if the background image has been set via the background CSS property instead of the background-image CSS property. As MDN notes, background is just a shorthand for setting other properties and a background image set through it will be correctly reflected in the value of the background-image property. By the way, +1. I note that this question languished without a correct answer for four years before you came along, and unambigously wrong answers accrued votes.
1
var image = $('#page').css('background-image');

Should do the job.

2 Comments

This doesn't quite answer the question, unlike steffanj's superior answer. -1
It does answer the question and should be the accepted answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.