【问题标题】:"Traversing DOM" nextSibling property not working. (Javascript) [duplicate]“遍历 DOM”nextSibling 属性不起作用。 (Javascript)[重复]
【发布时间】:2015-10-15 15:50:46
【问题描述】:

JS nextSibling 属性对我不起作用。

HTML:

<!DOCTYPE html>
<html lang="en-US">
    <head>
        <title>DOCUMENT OBJECT MODEL</title>
        <meta charset="UTF-8">
        <link rel="stylesheet" type="text/css" href="css.css">
    </head>
    <body>
        <ul>
            <li class="sameClass" id="one">first list item</li>
            <li class="sameClass" id="two">second list item</li>
            <li class="sameClass" id="three">third list item</li>
            <li class="sameClass" id="four">fourth list item</li>
        </ul>
        <div id="getValues"></div>
        <script src="javascript.js"></script>
    </body>
</html>

CSS:

li.sameClass{
    background-color:black;
    color:white;
}
li.targetClass{
    background-color:orange;
    color:red;
}

JS:

var element = document.getElementById("one").nextSibling;
element.className = "targetClass";

此代码应该通过将其 className 更改为“targetClass”来更改带有 id="two" 的第二个列表项的外观。这不起作用,document.querySelector("#one") 也不起作用。

可能是什么问题?

【问题讨论】:

  • id为one的节点的下一个兄弟节点是一个文本节点。

标签: javascript css dom siblings


【解决方案1】:

不要使用nextSibling,而是使用nextElementSibling

nextSibling - 查找下一个兄弟,即使它不是元素(即文本节点)

nextElementSibling - 查找下一个是元素的兄弟。

【讨论】:

  • 那行得通.... Thnx.. 但你能解释一下吗?
  • 好的,知道了。感谢您的帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-01-15
  • 1970-01-01
  • 1970-01-01
  • 2017-08-30
  • 1970-01-01
  • 2018-08-28
  • 1970-01-01
相关资源
最近更新 更多