Search code examples
javascripthtmldomtraversalnextsibling

Javascript DOM,accesing the textnode of the <li>element using nextsibling property


<body>
    <div id="li-container">
        <ul>
            <li class="hot">item1</li>
            <li id="secLi" class="cool">item2</li>
            <li class="cool">item3</li>
            <li class="cool">item4</li>
        </ul>
    </div>

<script language="javascript" type="text/javascript">
var secLi = document.getElementById("secLi");
var sib = secLi.nextSibling;
document.write(sib);

//OR //OR  //OR //OR  //OR //OR  //OR //OR  

var secLi = document.getElementById("secLi");
var sib = secLi.nextSibling;
document.write((sib).textContent);

</script>
</body>

I want to get the textnode of the third list(li) item using nextSibling property and write in the document.I know I can use "li.textContent" to access it but I want it this way.

No,I am not looking for "nextElementSibling",I want to acess the "textNode" of "secondli" using "nextSibling" property and that is because if I want to get to the "third li",I must use "nextSibling.nextSibling"twice to get to the "third li".(1)First "nextSibling" is for the "text-node" of the "2nd li" and (2)Second "nextSibling" is for the "3rd li".So I am not able to get the text-node of "2nd li" using "next-sibling" once.

I used text-fixer.com to remove other white-spaces and line breaks even then it dosent work.


Solution

  • Are you perhaps looking for nextElementSibling?

    var secLi = document.getElementById('secLi');
    secLi.nextSibling; // Is a text node.
    secLi.nextElementSibling; // Is the <li> you're looking for, so..
    secLi.nextElementSibling.textContent; // Gives you "item3"
    

    Update

    To better understand why you want nextElementSibling instead of nextSibling look at what the parent <ul> says its childNodes are:

    secLi.parentElement.childNodes;
    // [#text, <li>, #text, <li>, #text, <li>, #text, <li>, #text]
    

    You don't want the nextSibling because it's just the empty text between list items. You want the next element (list item).

    See https://developer.mozilla.org/en-US/docs/Web/API/NonDocumentTypeChildNode/nextElementSibling