views:

34

answers:

4

I'm trying to select a div with a certain background image this is what I have so far. Not working. Any ideas of what I'm doing wrong? I'm trying to follow the jQuery documentation.

var markerShadow0 = $("div[background-image='url(\"http://www.axtsweapons.com/gmarkers/markershadowA.png\")]");
A: 

Are you missing a single tick after the closing parenthesis for the url? I see an opening tick, but no closing one.

Henry
A: 

Background image isn't an attribute of a division, it is an attribute of a style. That means you would have to grab the division with that style.

Kerry
A: 

I don't believe you can treat CSS properties as attributes, which is what you're doing with the div[attribute=value] selector.

You might be able to get div[style*=background-image:url(http://...)] to work (see this), but you'd probably be better off with something like:

$('div').each(function(i, e) {
  if ($(e).css('background-image') == 'http://www.axtsw...dowA.png')) {
    // element matches
  }
});

Note that this will check every div on the page. If you can select some common parent element by ID you'll drastically reduce the number of elements you'll be iterating over.

meagar
+1  A: 

background-image is not an attribute of the element but a css style.

You will have to iterate all divs and check the css style.

$("div").each( function(){

   if ( $(this).css('background-image') === 'http://www.axtsweapons.com/gmarkers/markershadowA.png' ) {

      //do something

      //stop loop
      return false;

   }


});
redsquare
This worked great thanks! BTW I know that one equal sign is assignment and two is comparison but what is three?
abemonkey
@abemonkey - it is a strict equals operator, it only returns true if both the operands are equal and of the same type.
redsquare
The problem with this solution that I've found today is that it doesn't play well with any browser other than Firefox (that's the browser I've been developing in). Got any ideas why?
abemonkey
@abemonkey maybe the other browsers are not giving you the full url you may need to parse out the image name and just compare these
redsquare
Parsing would be ideal as I'm making a google maps application and would like to have different marker colors at some point. So keying off of the last letter in the div's background image name would be perfect. I looked up jQuery parsing online and just get stuff about parsing xml. Could you give me a quick example? Specific to this case would be great! thanks for all your help!!
abemonkey