views:

55

answers:

1

Hey Guys (and Ladies)

I want to select an image (with jQuery) by the src attribute. The Image is inside an ul and a collection of div's. The id of the ul is "sortable".

Here is my HTML:

<ul id="sortable">
  <li id="pic_0">
    <div class="sortEleWrapper">
      <div class="imgWrapper">
        <img src="/test1.jpg">
      </div>
      <input type="text" name="picText" id="picText" value="""" style="width:105px;color:#aaa" class="sortInput">
    </div>
    <input type="hidden" id="picSrc" name="picSrc" value="/test1.jpg">
  </li>
</ul>

etc.

and here is my js:

if($('#sortable').find('img[src="/test1.jpg"]').length > 0){
    alert('img exists');
}else{
    alert('img dosnt exists');
}

My problem is, that they don't find any image. But if I write the js like this:

if($('img[src="/test1.jpg"]').length > 0){
    alert('img exists');
}else{
    alert('img dosnt exists');
}

so they find the image. Can anybody help me plz.

PS: sorry for my poor english, but I'm german =)

+2  A: 

I'm not sure why the difference, but try using the $= attribute ends with selector.

Seems to work.

Example: http://jsfiddle.net/bTf7K/

$('#sortable').find('img[src$="/test1.jpg"]')

EDIT: The difference may have something to do with the method of getting the attribute value that jQuery uses at different times.

Using native methods:

element.getAttribute("src") // returns the actual value that was set

element.src // returns the value but with the full domain path

So I'm guessing jQuery uses both of these at different times.

patrick dw
I don't believe this is the problem. He notes that his problem has to do with his parent selector. EDIT: I take that back. I see your point. Perhaps there's an open bug-report for this.
BBonifield
@BBonfield - Test my example. It corrects the problem. The `<img>` is clearly a descendant of `#sortable`, yet doing `.find('img[src="/test1.jpg"]')` fails, while `.find('img[src$="/test1.jpg"]')` succeeds. Here's the failing test: http://jsfiddle.net/bTf7K/3/
patrick dw
yes, it works with the $. Thank you!!!!!
Neoklosch
@Patrick I revised the comment and adjusted my vote.
BBonifield
@Neoklosch - You're welcome. :o)
patrick dw
@BBonfield - Thanks. It must have something to do with how jQuery gets the attribute value on different occasions. Using native methods, `element.getAttribute("src")` returns the actual value that was set, while `element.src` returns the URL with the full domain path. I think you're right that there should be a bug report if there isn't one already.
patrick dw
Known bug! See http://forum.jquery.com/topic/src-attribute-selector-fails-on-img-tag-when-combined-with-a-direct-descendant-selector
Roatin Marth
@Roatin - Thanks for finding it. I was too lazy to look. :o)
patrick dw