Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Andrew Lundy
Andrew Lundy
13,269 Points

previousSibling vs previousElementSibling?

What's the difference between the two? Have been reading MDN docs and can not come up with how they operate differently. I've always used 'previousElementSibling' - but I am very curious to see what the difference is.

1 Answer

Hi Andrew, its how the property is returned that's different.

take this example:

    <ul>
        <li>List item 1</li>
        <li id="active">List item 2</li>
        <li>List item 3</li>
    </ul>

previousElement

This returns the node as an element, text or comment node:

var listItem = document.getElementById("active")
var previousElement = listItem.previousSibling;

console.log(previousElement);

this result in the console, a text node:

#text
    assignedSlot: null
    baseURI: "http://127.0.0.1:5500/"
    childNodes: NodeList []
    data: "↵        "
    firstChild: null
    isConnected: true
    lastChild: null
    length: 9
    nextElementSibling: li#active
    nextSibling: li#active
    nodeName: "#text"
    nodeType: 3
    nodeValue: "↵        "
    ownerDocument: document
    parentElement: ul
    parentNode: ul
    previousElementSibling: li
    previousSibling: li
    textContent: "↵        "
    wholeText: "↵        "
    __proto__: Text

previousElementSibling

This returns the node as an element node

var listItem = document.getElementById("active")
var previousElementSibling = listItem.previousElementSibling;

console.log(previousElementSibling);

The result in the console, an element node:

<li>List item 1</li>

So the difference between them is the level of specificity as to what to return