Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery select img with src

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 doesnt 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 doesnt exists'); } 

so they find the image.

like image 430
Neoklosch Avatar asked Sep 20 '10 15:09

Neoklosch


People also ask

How to src to image with jQuery?

Answer: Use the jQuery attr() Method You can use the attr() method to change the image source (i.e. the src attribute of the <img> tag) in jQuery. The following example will change the image src when you clicks on the image.

How to set image path in jQuery?

When you are using jQuery, you can easily get the absolute path of the image using 'src' attribute. With jQuery 1.6 or higher version, a new method called 'prop()' was introduced. So using prop(), one can get value of src. $(document).

How to add image using jQuery?

With jQuery, you can dynamically create a new image element and append it at the end of the DOM container using the . append() method. This is demonstrated below: jQuery.


1 Answers

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.

like image 137
user113716 Avatar answered Sep 21 '22 05:09

user113716