Javascript 如何更改第一个子级的属性
我可以更改此元素的背景色:Javascript 如何更改第一个子级的属性,javascript,css,parent-child,Javascript,Css,Parent Child,我可以更改此元素的背景色: <div onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;"> </div> 但我想改变第一个孩子的颜色,我认为应该是这样: <div onmouseover="this.firstC
<div onmouseover="this.style.backgroundColor='blue'" onmouseout="this.style.backgroundColor='red'" style="background-color:green; width:100px; height:40px;">
</div>
但我想改变第一个孩子的颜色,我认为应该是这样:
<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>
我想这是第一个孩子。
但它不起作用。怎么了?我怎样才能改变第一个孩子的风格
PS:稍后我想为子对象使用display=block和none以及其他一些属性(不仅仅是样式)。该颜色仅用于测试。您需要使用
.firstElementChild
,或者您需要去掉格式空白。该空白变为文本节点,即.firstChild
一些较旧的浏览器不支持.firstElementChild
属性,因此如果您支持这些属性,则需要使用函数对其进行填充
正如“系统”所提到的,您的目标是文本节点而不是元素节点。尝试使用
children[0]
而不是firstChild
请停止使用内联CSS/JavaScript。这不再是软件的编写方式。/同意@meagar。另外,请使用javascript库或框架,如jquery@Populus:您为什么推荐JavaScript库?你无法知道情况是否需要这样做。@系统哈哈,但Javascript库解决了所有问题!尤其是一个小问题。这太值得了。所有30-100Kb:)@Populus都是正确的,但兼容性与此特定问题无关。这是对第一个孩子在这种情况下的理解。显然,有一个相当简单的解决方案(感谢答案)不应该有跨浏览器的问题…并且不需要库。或者循环子元素,找到第一个不是文本节点的元素?谢谢你的回答。两个答案我都喜欢,不知道该接受哪一个。@erik:去接受另一个吧。这对我来说真的不重要。但是请注意,一些IE版本在
.children
方面有一个怪癖,因为它将包含注释节点。如果没有HTML注释,则不是问题。FF3不支持它,但在这一点上这几乎不是问题。有关更多兼容性信息,请访问子项的浏览器兼容性列表:
<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;
}