我有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
必须有效为null
或empty
,这意味着我在'add'之前遍历DOM的方法通话没有成功。
我拥有HTML:
previousSibling
方法正在返回一个空的文本节点(除空白外仅包含空白),该节点不具有classList
属性。您可以将其更改为previousElementSibling
以获取按钮元素。
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元素内添加类。我会推荐你;
button.setAttribute("class", "dropbtn ANY-OTHER-CLASS")
尝试一下: