6

How can I get the distance between two elements in the DOM?

I am thinking on using getBoundingClientRect, but I fail to see how can I use that in order to calculate the distance between two elements. So, for example, how close is a from an .

Hommer Smith
  • 26,772
  • 56
  • 167
  • 296

1 Answers1

9

Pretend you have a div with id div1 and a div with id div2. You could calculate the distance (in pixels) from div1's center to div2's center with some simple math...

// get the bounding rectangles
var div1rect = $("#div1")[0].getBoundingClientRect();
var div2rect = $("#div2")[0].getBoundingClientRect();

// get div1's center point
var div1x = div1rect.left + div1rect.width/2;
var div1y = div1rect.top + div1rect.height/2;

// get div2's center point
var div2x = div2rect.left + div2rect.width/2;
var div2y = div2rect.top + div2rect.height/2;

// calculate the distance using the Pythagorean Theorem (a^2 + b^2 = c^2)
var distanceSquared = Math.pow(div1x - div2x, 2) + Math.pow(div1y - div2y, 2);
var distance = Math.sqrt(distanceSquared);
Cameron Askew
  • 1,403
  • 1
  • 12
  • 20
  • 8
    This answer is using jQuery...but if you don't want to use jQuery you could replace the top 2 lines with `var div1rect = document.getElementById("div1").getBoundingClientRect();` ...etc – Cameron Askew Oct 29 '13 at 23:56
  • I basically need the distance to estimate how likely is a "price" on a site be the price of the product that the site is for. I want to calculate distance between the product image (which I know where is it) and all the prices that are around the page. The price that is closest to the product image is likely to be the price of that product :) – Hommer Smith Oct 30 '13 at 16:04
  • I am trying it. I will be back and tell you. Thanks :) – Hommer Smith Oct 30 '13 at 17:07
  • Thanks for the answer. The problem here is that some elements (span) don't have width/height. – Hommer Smith Jan 30 '14 at 18:41
  • Are you in control of the HTML? If not, I would find another way to get a reasonable location of the price, maybe just use top/left and not using the width/height to get a center point. – Cameron Askew Jan 30 '14 at 19:21
  • WHat? I don't understand. How would you do it without with/height? – Hommer Smith Jan 30 '14 at 20:30
  • That depends. Is just using the top/left point of the span good enough? If you have control over the HTML, modify the HTML so that the span's are wrapped inside a div. – Cameron Askew Jan 30 '14 at 23:58
  • You can get width by subtracting left from right, and you can get height by subtracting top from bottom. – Quentin Engles Oct 11 '17 at 00:34