我有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的方法没有起作用。
发布于 2020-02-12 17:45:35
previousSibling
方法返回的是一个空的文本节点(只包含空格),该节点不是元素,也没有classList
属性。无论前一个节点是不是元素,previousSibling
都会返回它。您可以将其更改为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>
发布于 2020-02-12 17:49:21
你可以使用...
var button = document.querySelector(".dropbtn")
这将获得类为dropbtn的第一个元素(本例中的button元素)。
如果您试图在button元素中添加一个类。我推荐你;
button.setAttribute("class", "dropbtn ANY-OTHER-CLASS")
发布于 2020-02-12 17:45:44
试试这个:
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>
当你访问像parentNode
或previousSibling
这样的HTML DOM节点的属性时,你也会得到像文本节点这样的非HTML节点,在你的代码中,每一个新行都会创建一个空的文本节点,因此你得到的是它而不是所需的元素。
https://stackoverflow.com/questions/60194087
复制