[英]HTML & CSS - DOM traversal
我有 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 遍歷方法沒有工作。
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>
您可以使用...
var button = document.querySelector(".dropbtn")
這將獲得類 dropbtn 的第一個元素(本例中的按鈕元素)。
如果您嘗試在按鈕元素中添加一個類。 我會推薦你;
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 節點的屬性(如parentNode
或previousSibling
您還將獲得非 HTML 節點(如 Text 節點),在您的代碼中,每個新行都會創建一個空的 Text 節點,因此您將獲得它而不是所需的元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.