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:
<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>
//Should add "next" class attribute to the "Contact Us" li tag.
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!
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
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");