views:

28

answers:

2

I'm tying to select images based on their URLs, but for some reason it's not playing ball:

Ultimately I'm after something like:

var imgs = $("img[@src='images/object.png']:not(:hidden)");

But even with something simple like:

$("img[@src='images/object.png']");

This error is thrown: "TypeError: Object doesn't support this property or method".

If I omit the @ from the query:

$("img[src='images/object.png']");

I get no items returned. I've copied and pasted the path directly from the generated html at runtime and it still refuses to return any items. If I replace the src selector with an id selector, it returns the items.

This is the image tag generated at runtime:

<img id="ctl00_ContentPlaceHolder1_object_1" src="images/object.png" style="height:16px;width:16px;border-width:0px;visibility:visible;display:inline;margin-right:3px;" />

I'm running jQuery 1.4.2 and I've checked all the documentation and all appears to be coded correctly. I'm assuming this isn't a bug, but a misinterpretation on my part. Can anyone she any light on this?

Cheers

+2  A: 

Don't use the @ and be sure to include the full query too. If there is one.

$("img[src='/images/marketing/logo.png?1277792289']")[0]

You can do substring matching as well

$("img[src*='logo']")[0]

And the :not selector is in the wrong place. It should not be in the attribute brackets.

$("img[src*='logo']:not(:visible)")[0]
The Who
Also the `:not(:hidden)` should come outside the `]`, like: `img[src='images/object.png']:not(:hidden)`
casablanca
Correct, added it to the answer.
The Who
@casablanca: This was an error introduced in my writing of the question, in my original code, that was correct. I've fixed it in my example. Sorry about the confusion.
BenAlabaster
@The Who: Interestingly if I remove the folder and use *= instead of a straight ='images/file.png' it works... is that something to do with the path I'm using?
BenAlabaster
@BenAlabaster I guessing here, but maybe the image is being translated as an absolute path? So the document root is "/foo/bar" the image is "images/file.png" jQuery might consider the src to be "/foo/bar/images/file.png"? Likewise if you are "/" the image src would be "/images/file.png". A big guess, but its all I got!
The Who
@The Who: Thanks, I'll have a play with it and see if I can figure it out.
BenAlabaster
+1  A: 

This used to be a bug in jQuery and apparently it still is.

Check out the following tickets:

Essentially, what you have will work if you use the attributeEndsWith ($) or attributeContains (*) selectors because jQuery is not comparing your string against exactly what you put into the image src attribute, but against the full url path (ie, http:// ..... /images/object.png)

Paolo Bergantino