HTML & CSS - DOM 遍历

Kyl*_*rce 1 html javascript dom

我有 HTML:

<div class="dropdown">
  <button class="dropbtn">Game Design</button>
  <div class="dropdown-content">
    <a id="GameIdea" href="GameIdea.html">Link 1</a>
    <a id="GameMechanics" href="GameMechanics.html">Link 2</a>
    <a id="GameCharacters" href="GameCharacters.html">Link 3</a>
    <a id="Inspiration" href="Inspiration.html">Link 3</a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

和 JavaScript:

var anchor = document.getElementById(pathShort); //e.g. pathShort == GameIdea
var anchorParent = anchor.parentNode;
var button = anchorParent.previousSibling;
button.classList.add("active");
Run Code Online (Sandbox Code Playgroud)

问题是这样的 - 我不想要锚元素:document.getElementById(pathShort);

我想要按钮元素,因此正如您所看到的,我anchor.parentNode;用来获取div锚点所在的 ,然后anchorParent.previousSibling;获取 , 旁边的元素div,而不是之后。

在我看来,我认为这会起作用,但在控制台中我得到了错误Cannot read property 'add' of undefined,因此变量button必须有效nullempty,这意味着我在“添加”调用之前的 DOM 遍历方法不起作用。

Bor*_*ric 5

previousSibling方法返回一个空文本节点(只包含空格),它不是一个元素并且没有classList属性。previousSibling返回前一个节点,无论它是否是元素。您可以将其更改previousElementSibling为获取按钮元素,因为它仅返回前一个元素,而忽略其他类型的节点。

var pathShort = "GameIdea";
var anchor = document.getElementById(pathShort);
var anchorParent = anchor.parentNode;
var button = anchorParent.previousElementSibling;
button.classList.add("active");
Run Code Online (Sandbox Code Playgroud)
<div class="dropdown">
  <button class="dropbtn">Game Design</button>
  <div class="dropdown-content">
    <a id="GameIdea" href="GameIdea.html">Link 1</a>
    <a id="GameMechanics" href="GameMechanics.html">Link 2</a>
    <a id="GameCharacters" href="GameCharacters.html">Link 3</a>
    <a id="Inspiration" href="Inspiration.html">Link 3</a>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)