27

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.

zhulien
  • 5,145
  • 3
  • 22
  • 36
QMaster
  • 3,743
  • 3
  • 43
  • 56

1 Answers1

41

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>
QMaster
  • 3,743
  • 3
  • 43
  • 56
NullPointer
  • 7,094
  • 5
  • 27
  • 41