Take the 2-minute tour ×

I have a <div> that on occasion has an inline background attribute applied to it.

I would like to be able to check if there is an inline style attached to it, and if there is then I want to go ahead and attach a background-position.

Is there a way that I can check explictly for inline backgrounds applied to $(this)?

if ($(this).css('background').length > 0) { 
   console.log('has a background'); 
   // set a background position
   $(this).css('background-position', 'center 22px');
share|improve this question
you could parse through the value of the style-attribute of the element –  Sven Bieder Feb 7 '13 at 14:12
What do you mean by "inline" : not defined into CSS class? –  sdespont Feb 7 '13 at 14:14
@sdespont Yes, inline is when it is defined in the markup, i.e. style="background: url('www.crmpicco.co.uk');" –  crmpicco Feb 7 '13 at 14:15
Have you looked at this question? stackoverflow.com/questions/476730/… –  corvec Feb 7 '13 at 14:16
Ok, but can't you apply your background-position in all cases? –  sdespont Feb 7 '13 at 14:16
show 5 more comments

2 Answers

up vote 4 down vote accepted

I bet something like this might work

if($(this).attr("style").indexOf("background") >=0){
  //we have inline background styles!
share|improve this answer
Yes, thanks Chris. That worked exactly like I hoped it would! –  crmpicco Feb 7 '13 at 14:20
add comment

You can test for inline styles using prop

if ($(this).prop('style').backgroundImage) {
  //.. do what you want to
share|improve this answer
This doesn't seem to work for me, Beat. –  crmpicco Feb 7 '13 at 14:24
@crmpicco just ran into it myself, the style prop actually allows for a much nicer approach. And I thought it would return a string. Edited the answer. –  Beat Richartz Feb 7 '13 at 14:28
add comment

Your Answer


