HTML & CSS - 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>

而 JavaScript:

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

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

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

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

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

var pathShort = "GameIdea";
var anchor = document.getElementById(pathShort);
var anchorParent = anchor.parentNode;
var button = anchorParent.previousElementSibling;
button.classList.add("active");
<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>

您可以使用...

var button = document.querySelector(".dropbtn")

这将获得带有类 dropbtn 的第一个元素(在本例中为 button 元素(。

如果您尝试在按钮元素中添加类。我会推荐你;

button.setAttribute("class", "dropbtn ANY-OTHER-CLASS")

试试这个:

const pathShort = 'GameIdea';
const anchor = document.getElementById(pathShort);
const anchorParent = anchor.parentElement;
const button = anchorParent.previousElementSibling;
button.classList.add("active");
<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>

当您访问 HTML DOM 节点的属性(如parentNodepreviousSibling(时,您还将获得非 HTML 节点(如文本节点(,在您的代码中,每个新行都会创建一个空的文本节点,因此您可以获得它而不是所需的元素。

最新更新