8

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

csalmeida
  • 528
  • 7
  • 26

1 Answers1

9

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");
Ram
  • 143,282
  • 16
  • 168
  • 197
  • So what's happening is that the `textNode` is being targeted instead of the `elementNode` and the reason is the line breaks and other hidden characters in the HTML code? I would never guessed that. Another quick question, do you think I should write the statements like you do as well? It seems easier to read. To finish up thank you so much for your support Vohuman, I want to let you know that having your support help me a lot understanding this language. – csalmeida Mar 02 '15 at 11:08
  • @cs.almeida You are very welcome! I'm glad I was able to help. Using that style of writing is really just a matter of personal preference. When I have a long line in a small file I use that style. It's more readable, maintainable and editable for me. – Ram Mar 02 '15 at 12:16