jQuery: How to find an image by its src

前端 未结 4 907
遇见更好的自我
遇见更好的自我 2020-12-07 22:08

I need to find an img by name and src. I have been trying the following to no avail.

var s = $(\"img[src=\'/images/greendot.gif\'][name=\'BS\']\");


        
相关标签:
4条回答
  • 2020-12-07 22:38

    Try losing the quotes:

    var s = $("img[src=../../images/greendot.gif][name=BS]");
    
    0 讨论(0)
  • 2020-12-07 22:43

    without seeing the html I would say check your path.

    $("img[src$='greendot.gif'][name='BS']")
    

    given the following HTML:

    <img src="http://assets0.twitter.com/images/twitter_logo_header.png" name="logo" />
    

    this jquery worked:

    var x = $("img[src$='twitter_logo_header.png'][name='logo']");
    alert(x.attr("src"));
    
    0 讨论(0)
  • 2020-12-07 22:50

    Change your img tag like this:

    <img src="path/to/imgage/img.jpg" title="img.jpg" />
    

    I mean add to your images title attribute and set them name of file.

    When you need to access sertain image you can do it as below:

    //Finding image that you need using 'title' attribute; 
    var imageTag = $("img[title='imageName']");
    
    //Then if you need to do something with it;
    imageTag.attr('src', 'path/to/newImage/newImage.jgp');
    imageTag.attr('title', 'newImage.jpg');
    
    0 讨论(0)
  • 2020-12-07 23:05

    Browsers add full path to src, href and similar attributes. So even though element is defined with relative path, in DOM 'src' attribute contains domain name and full path. Using [src$="..."] syntax or specifying full domain name seem to be only options for finding images by src with jQuery.


    I might be wrong here. src property of image object reports full path, but the attribute should contain path as specified in the code. [src="relative/path"] works in the latest jQuery version, maybe it was an early version where it didn't work.

    0 讨论(0)
提交回复
热议问题