开发者

Is there any way to access parent dom object from the child element?

开发者 https://www.devze.com 2022-12-21 19:35 出处:网络
I have a simple DOM code like the following <div> <div> </div> </div> I want to set the background color of the outer div using the inner div alone. Is it possible? The ques

I have a simple DOM code like the following

<div>
    <div>
    </div>
</div>

I want to set the background color of the outer div using the inner div alone. Is it possible? The question might be a bit crazy. But I have a strong reason behind asking that. I am working on a framework where there are html code generated dynamically and I hardly have control over it. But I can put inner elements. In the example above, the outer div would be from my generated code 开发者_Python百科and I want to change the backgroud color, I cannot do it directly. So I want to do it via the child div.

Something like childDiv.parent.background-color = blue.

Is this feasible? Or a similar implementation would be of immense help!


In this article it is explained how to surf the DOM tree.

You're probably interested in the parentNode attribute.


<div>
    <div>

    </div>
</div>

childDiv.parentNode.style.backgroundColor="blue";


Relative DOM manipulation is great stuff and well worth learning.

JavaScript frameworks make this really easy. For example (using Prototype): (jQuery has similar actions)

<div>
<a href="javascript://" onclick="$(this).up().style.backgroundColor='blue'">Make it blue</a>
</div>

You can then do things like:

$(this).up(2) - to go up two levels

$(this).down()
$(this).next()
$(this).previous

or even:

$(this).up('.someclass') - this goes up the tree until it finds the first element with class "someClass"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号