最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How can I quickly find the relatively positioned HTML parent element of an absolutely positioned child? - Stack Ove

programmeradmin6浏览0评论

I am working with the following code:

<div>
    <div>
        <div>
            <div>
                <div>
                    <div>
                        ...
                            <div class="absolute">Lorem ispum</div>
                        ...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

.absolute {
  position: absolute;
}

Using Chrome's DevTools, I'd like to be able to quickly find which parent <div> element has position: relative, so I can know which parent element is determining the origin point of my absolutely positioned element. I can manually inspect each of the divs to find the first parent that is set to relative but I'm working with a deeply nested tree, so I'm wondering if there is a faster way to find the parent I'm trying to find. A Javascript snippet for the console would be an example of a suitable solution.

I am working with the following code:

<div>
    <div>
        <div>
            <div>
                <div>
                    <div>
                        ...
                            <div class="absolute">Lorem ispum</div>
                        ...
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

.absolute {
  position: absolute;
}

Using Chrome's DevTools, I'd like to be able to quickly find which parent <div> element has position: relative, so I can know which parent element is determining the origin point of my absolutely positioned element. I can manually inspect each of the divs to find the first parent that is set to relative but I'm working with a deeply nested tree, so I'm wondering if there is a faster way to find the parent I'm trying to find. A Javascript snippet for the console would be an example of a suitable solution.

Share Improve this question asked Mar 23, 2015 at 19:03 Blake FrederickBlake Frederick 1,67021 silver badges32 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

HTMLElement.offsetParent is just designed to do this.

See this document on MDN.

To add to Justineo's answer, if you want to do this in Chrome Devtools:

Right-click the element in the "Elements" section of the devtools and select "Store as global variable":

It should store a JavaScript variable reference to the element as "temp1":

Then just run temp1.offsetParent in the console to see the parent:

发布评论

评论列表(0)

  1. 暂无评论