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 badges5 Answers
Reset to default 3If 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
版权声明:本文标题:javascript - getting img element from known source - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741688589a2392588.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论