当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Working with previousSibling and nextSibling to set attributes

问题描述:

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 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");
分享给朋友:
您可能感兴趣的文章:
随机阅读: