开发者社区> 问答> 正文

JS lastChild不能动态添加样式是怎么回事?

<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

是怎么回事呢

展开
收起
杨冬芳 2016-06-16 15:51:57 2028 0
1 条回答
写回答
取消 提交回答
  • IT从业
    <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>

    screenshot

    上述的 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

    我表达的是否清楚了?

    2019-07-17 19:41:08
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
JavaScript异步编程 立即下载
Delivering Javascript to World 立即下载
编程语言如何演化-以JS的private为例 立即下载