csalmeida
csalmeida

Reputation: 628

Working with previousSibling and nextSibling to set attributes

I started studying JavaScript ad 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 to 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 misspelt.

Anyway thanks for your time and help in advance!

Upvotes: 8

Views: 7621

Answers (1)

Ram
Ram

Reputation: 144659

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");

Upvotes: 9

Related Questions