Search code examples
javascriptdomcompareelementsiblings

Difference between previoussibling and previouselementsibling-javascript


I wonder if I know What is the difference between javascript previousSibling and previousElementSibling. I tried and I didn't find any question or article that compare or describe this. Maybe this is for my little javascript knowledge, but I appreciate if explain it.

Thanks so much.


Solution

  • The previousElementSibling property returns the previous element of the specified element, in the same tree level.

    The difference between this property and previousSibling, is that previousSibling returns the previous sibling node as an element node, a text node or a comment node, while previousElementSibling returns the previous sibling node as an element node (ignores text and comment nodes).

    //Get the second li element
    var liElement = document.getElementById( "target" ) ;
    
    //Get the previous element (→ Text node (line feed and tab character))
    var previousSibling = liElement.previousSibling ;
    console.log("previousElementSibling::"+previousSibling.data);
    console.log("previousSibling.previousElementSibling::",previousSibling.previousElementSibling);
    
    //Get the previous element (→ <li> Element 3 </ li>)
    var previousElementSibling = liElement.previousElementSibling ;
    console.log("previousElementSibling::",previousElementSibling);
    <ul>
    	<li>Element-1</li>↓
    	<li id="target">Element-2</li>
    	<li>Element-3</li>
    </ul>