Find coordinates of every link in a page
-
09-06-2019 - |
Question
In Javascript: How does one find the coordinates (x, y, height, width) of every link in a webpage?
Solution
Using jQuery, it's as simple as:
$("a").each(function() {
var link = $(this);
var top = link.offset().top;
var left = link.offset().left;
var width = link.offset.width();
var height = link.offset.height();
});
OTHER TIPS
without jquery:
var links = document.getElementsByTagName("a");
for(var i in links) {
var link = links[i];
console.log(link.offsetWidth, link.offsetHeight);
}
try this page for a func to get the x and y values: http://blogs.korzh.com/progtips/2008/05/28/absolute-coordinates-of-dom-element-within-document.html
However, if you're trying to add an image or something similar, I'd suggest using the a:after css selector.
Plain JavaScript:
function getAllChildren (node, tag) {
return [].slice.call(node.getElementsByTagName(tag));
}
function offset(element){
var rect = element.getBoundingClientRect();
var docEl = doc.documentElement;
return {
left: rect.left + window.pageXOffset - docEl.clientLeft,
top: rect.top + window.pageYOffset - docEl.clientTop,
width: element.offsetWidth,
height: element.offsetHeight
};
}
var links = getAllChildren(document.body, 'a');
links.forEach(function(link){
var offset_node = offset(node);
console.info(offset_node);
});
With jQuery:
$j('a').each( findOffset );
function findOffset()
{
alert
( 'x=' + $j(this).offset().left
+ ' y=' + $j(this).offset().top
+ ' width=' + $j(this).width()
+ ' height=' + $j(this).height()
);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow