so since I started studying JavaScript I've been reading this book called Learning JavaScript by Tim Wright.
In this book I found a chapter about how we can move and target elements in the DOM tree and one of them is making use of properties which target siblings, while doing the exercises in the book I simply could not make the following statement work:
<ul id="nav">
<li><a href="/" id="home">Home</a></li>
<li><a href="/about" id="about">About Us</a></li>
<li><a href="/contact" id="contact">Contact Us</a></li>
</ul>
<script>
//Should add "next" class attribute to the "Contact Us" li tag.
document.getElementById("about").parentNode.nextSibling.setAttribute("class", "next");
</script>
After having a quick look at this code I was wondering if any of you more experienced developers could help me and explain me why this doesn't work properly. I feel confused because I can't know whether I'm doing something wrong or the article about these properties is misspelled.
Anyway thanks for your time and help in advance!
Cheers!
cs.almeida
nextSibling returns the next node (an element node, a text node or a comment node). Whitespace between elements are also text nodes. nextElementSibling returns the next element (not text and comment nodes).
Sibling. A sibling is an element that shares the same parent with another element.
The article Whitespace in the DOM contains more information about this behavior. You can use Element. nextElementSibling to obtain the next element skipping any whitespace nodes, other between-element text, or comments.
nextSibling
selects the very next sibling of the element. The very next sibling node can also be a textNode
that doesn't have setAttribute
method, i.e. what your code tries to do is adding a class to the next sibling textNode. If you remove the line break and other hidden characters between the 2 li
elements then you code will work as expected.
Another option is using the nextElementSibling
property instead of the nextSibling
, which will select the next sibling node that has nodeType
of 1
, i.e. the next HTMLElement
sibling of the element.
document.getElementById("about")
.parentNode
.nextElementSibling
.classList // https://developer.mozilla.org/en-US/docs/Web/API/Element/classList
.add("next");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With