erik
erik

Reputation: 2446

how to change a property of the first child

I am able to change the background-color of this element:

<div onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
</div>

But I want to change the color of the first child, which I assumed should work like this:

<div onmouseover="this.firstChild.style.backgroundColor='blue'" onmouseout="this.firstChild.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">

  <div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>

</div>

But it does not work. What is wrong? How can I change the style of the firstChild?

PS: I later want to use display=block and none and some other propertys (not just style) for the child. The color was just for testing.

Upvotes: 0

Views: 6838

Answers (2)

the system
the system

Reputation: 9336

You would need to use .firstElementChild, or you'd need to get rid of the formatting whitespace. That whitespace becomes a text node, which is the .firstChild.

The .firstElementChild property isn't supported by some older browsers, so if you're supporting those, you'd need to shim it with a function.


<div onmouseover="changeColor(this, 'blue')" onmouseout="changeColor(this, 'red')" style="background-color:green; width:100px; height:40px;">

  <div style="background-color:white; height:10px; width:10px; margin:20px;">This is the first child, I think.</div>

</div>

function changeColor(el, color) {
    firstElemChild(el).style.backgroundColor=color;
}
function firstElemChild(el) {
    if (el.firstElementChild)
        return el.firstElementChild;

    el = el.firstChild

    while (el && el.nodeType !== 1)
        el = el.nextSibling;

    return el;
}

Upvotes: 3

showdev
showdev

Reputation: 29168

As "the system" mentioned, you are targeting a text node rather than an element node. Try using children[0] instead of firstChild.

jFiddle here

Upvotes: 4

Related Questions