javascript - JS lastChild不能动态添加样式是怎么回事?
迷茫
迷茫 2017-04-10 15:12:07
[JavaScript讨论组]
<ul id="test">
    <li></li>
    <li></li>
    <li></li>
    <li></li>
</ul>

有如上结构html, document.getElementById('test').lastChild.style 这样添加样式,
在google里面报的错误是: Cannot read property 'style' of undefined

是怎么回事呢

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

全部回复(2)
ringa_lee
<script>
window.onload = function(){
    document.getElementById("test").lastChild.style.color = "red";
}
</script>
<ul id="test"><li>1</li><li>2</li><li>3</li><li>4</li></ul>

上述的 DOM 结构若执行 document.getElementById("test").lastChild.nodeName // 返回 LI

DOM 若为

<ul id="test">
    <li>1</li>
    <li>2</li>
    <li>3</li>
    <li>4</li>
</ul>

执行 document.getElementById("test").lastChild.nodeName // 返回 #text

属性节点的 nodeName 与属性名相同,文本节点的 nodeName 始终是 #text

我表达的是否清楚了?

怪我咯

最后一个li标签和ul结束标签之间的空白也是ul的子节点

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号