admin管理员组

文章数量:1302902

say I have an img tag as follows in a web page

<img src = "">

is there a way for me to get this element by src in javascript? so something like document.elementFromSrc() or something like that? The goal after getting this img element is to find the x and y coordinate and such

say I have an img tag as follows in a web page

<img src = "https://www.google.">

is there a way for me to get this element by src in javascript? so something like document.elementFromSrc() or something like that? The goal after getting this img element is to find the x and y coordinate and such

Share asked Jan 18, 2012 at 17:07 aditadit 33.7k72 gold badges234 silver badges380 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 3

If you're unable to add an id, you could do:

var allImages = document.getElementsByTagName("img");
var target;
for(var i = 0, max = allImages.length; i < max; i++)
    if (allImages[i].src === "https://www.google."){
       target = allImages[i];
       break;
    }

But ideally you would just add an id to this img, and then get it with document.getElementById

Don't loop over all images in the document. Use query selector which uses regex to match the query string. Try this: document.querySelector('[src*="https://www.google.""]')

PS jquery has 94kb minified file size. Please don't include it unless there's a requirement.

No there isn't. You can iterate (for [MDN]) over all img elements (using getElementsByTagName [MDN]) and pare the src attribute or property against the URL you are searching for.

There is no function to get an element by an attribute value (at least, not a widely supported one, although XPath-like selectors might be mon soon). You can do a quick filter like so:

function getElementsByAttributeName(tagName, attributeName, attributeValue) {
  var i, n, objs=[], els=document.getElementsByTagName(tagName), len=els.length;
  for (i=0; i<len; i++) {
    n = els[i][attributeName];
    if (n && (n==attributeValue)) {
      objs.push(els[i]);
    }
  }
  return objs;
}
getElementsByAttributeName('img', 'src', 'http://www.google.'); // => [<a>]

I would remend using jQuery.

var offset = $('img[src="http://www.google."]').offset();

This gives you the x and y coordinates within the document. See documentation for offset() and position().

本文标签: javascriptgetting img element from known sourceStack Overflow