tags:

views:

38

answers:

3

Hi,

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 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!

+3  A: 

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

You're probably interested in the parentNode attribute.

Roberto Aloi
+1  A: 
<div>
    <div>

    </div>
</div>

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

Jonathan Czitkovics
Nice.. thats wat I was looking for!
Bragboy
No problem. Short and sweet and just what you need.
Jonathan Czitkovics
A: 

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"

Diodeus
-1: For simple DOM manipulation like this, you do not need a 26kb JavaScript library. I don't use bulldozers to remove a nail from my wall.
Andrew Moore
No, you don't, but it makes learning it a lot easier and makes coding it a lot easier and opens the doors to all kinds of benefits a framework brings. 26K, big whoop, a lot of images are larger than that. If being a Nazi purist makes you happy Andrew, go build your sites using a hex-editor.
Diodeus