How to get bounding box for div element in jQuery

JavascriptJqueryHtmlCssSvg

Javascript Problem Overview


I want to calculate bounding box for div element via jQuery/JavaScript.

I tried like this:

//Left side of box 
document.getElementById("myElement").offsetLeft; 
//Top side of box 
document.getElementById("myElement").offsetTop;  
//Right side of box
document.getElementById("myElement").offsetLeft + document.getElementById("myElement").offsetWidth; 
//Bottom side of box 
document.getElementById("myElement").offsetTop + document.getElementById("myElement").offsetHeight; 

It returns some values. whether it is correct way to get bounding box for div element via jQuery / JavaScript.

I need something like getBBox() method in SVG element. it will return x, y, width and height of an element. Sameway how can I get bounding box for div element?

Javascript Solutions


Solution 1 - Javascript

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

Solution 2 - Javascript

You can get the bounding box of any element by calling getBoundingClientRect

var rect = document.getElementById("myElement").getBoundingClientRect();

That will return an object with left, top, width and height fields.

Solution 3 - Javascript

using jQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSivaRajiniView Question on Stackoverflow
Solution 1 - JavascriptRycochetView Answer on Stackoverflow
Solution 2 - JavascriptRobert LongsonView Answer on Stackoverflow
Solution 3 - JavascriptArpit AgrawalView Answer on Stackoverflow