HTML和CSS-DOM遍历

问题描述 投票:0回答:3

我有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,这意味着我在'add'之前遍历DOM的方法通话没有成功。

我拥有HTML:

javascript html dom
3个回答
4
投票

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>

1
投票

您可以使用...

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

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

[如果您要在button元素内添加类。我会推荐你​​;

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


0
投票

尝试一下:

© www.soinside.com 2019 - 2024. All rights reserved.