I want to get the offset of an element relative to a specific parent not the direct one and not the document.
I looked for that on the internet and found the offset and position JQuery methods. But seems they don't help me in my situation ( relative to a specific parent)
Any help!
To get the offset position of an HTML element relative to its parent, you can use the offsetLeft and offsetTop properties of the element. Here is example: const div = document. querySelector('.
We can also use the jQuery position() method. The position() method is an inbuilt method in jQuery which is used to find the position of the first matched element relative to its parent element in the DOM tree.
The offset parent is the nearest ancestor that has a position other than static. If no offset parent exists, the offset parent is the document body.
The jQuery UI . position() method allows you to position an element relative to the window, document, another element, or the cursor/mouse, without worrying about offset parents. Note: jQuery UI does not support positioning hidden elements.
You can try this out:
var offsetLeft = $('#myElement').position().left - $('#myElement').closest('#crazyAncestor').position().left;
var offsetTop = $('#myElement').position().top - $('#myElement').closest('#crazyAncestor').position().top;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With