<html>
<head>
<style type="text/css">
.highlight {
background-color: blue;
}
</style>
<script type="text/javascript">
var my = document.getElementById('try');
my.firstChild.className = 'highlight'; //无效
//如果是=================
my.firstChild.parentNode.className = 'highlight'; //work!同时测试是否firstChild有错
</script>
</head>
<body>
<ul id='try'>
<li>aaaa</li>
<li>bbbb</li>
</ul>
</body>
</html>为什么这样设置my.firstChild.className = 'highlight';会没有任何效果?css节点classnode
<head>
<style type="text/css">
.highlight {
background-color: blue;
}
</style>
<script type="text/javascript">
var my = document.getElementById('try');
my.firstChild.className = 'highlight'; //无效
//如果是=================
my.firstChild.parentNode.className = 'highlight'; //work!同时测试是否firstChild有错
</script>
</head>
<body>
<ul id='try'>
<li>aaaa</li>
<li>bbbb</li>
</ul>
</body>
</html>为什么这样设置my.firstChild.className = 'highlight';会没有任何效果?css节点classnode
console.log("my.firstChild.nodeType=" +my.firstChild.nodeType);//=3就是说firstChild是一个文本节点,无法设置className .
<head>
<style type="text/css">
.highlight {
background-color: blue;
}
</style>
<script type="text/javascript">
window.onload = function ()
{
var my = document.getElementById('try');
my.firstChild.className = 'highlight';
}
</script>
</head>
<body>
<ul id='try'>
<li>aaaa</li>
<li>bbbb</li>
</ul>
</body>
</html>
在google,firefox下,空白行也算节点的,把HTML写成下面那样,不要换行就可以了。<ul id='try'><li>aaaa</li><li>bbbb</li></ul>
<head>
<style type="text/css">
.highlight {
background-color: blue;
}
</style>
<script type="text/javascript">
window.onload = function(){
var my = document.getElementById('try');
var nodes = my.childNodes;
for(var i = 0 ; i < nodes.length ; ++i){
if(nodes[i].nodeType==1){
nodes[i].className='highlight';
break;
}
}
}
</script>
</head>
<body>
<ul id='try'>
<li>aaaa</li>
<li>bbbb</li>
</ul></body>
</html>
不知道你是在什么浏览器下可以实现,我用你这代码在chrome,firefox,IE下都没有达到效果。