Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Direct native JavaScript or jQuery method to get containing block of an element

Is there a built-in DOM API or a jquery one to get the containing block of an element?

I am not asking how to get the containing block of an element. I am just asking if there's already the wheel so I don't have to re-invent it. If there isn't, I could just do:

let containingBlock = $("#five")
                      .parents()
                      .find(parent => parent.css("position") === ...);

for the following HTML, for example:

<div id = "one">
    <div id = "two" style = "position: absolute;">
        <div id = "three">
            <div id = "four">
                <div id = "five" style = "position: absolute;"></div>
            </div>
        </div>
    </div>
</div>
like image 764
Water Cooler v2 Avatar asked Nov 07 '22 14:11

Water Cooler v2


1 Answers

You can use offsetParent() to get the closest parent element that is positioned. According to the documentation, it works when the parent element is positioned absolute, relative, or fixed, but it also worked with sticky positioning for me.

like image 177
Roya Avatar answered Nov 14 '22 22:11

Roya