adit
adit

Reputation: 33674

getting img element from known source

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

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

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

Upvotes: 3

Views: 7025

Answers (5)

Sakhi Mansoor
Sakhi Mansoor

Reputation: 8122

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.com""]')

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

Upvotes: 2

Kekoa
Kekoa

Reputation: 28250

I would recommend using jQuery.

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

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

Upvotes: 0

maerics
maerics

Reputation: 156622

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 common 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.com'); // => [<a>]

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83366

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.com"){
       target = allImages[i];
       break;
    }

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

Upvotes: 3

Felix Kling
Felix Kling

Reputation: 817030

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

Upvotes: 1

Related Questions