Difference between previoussibling and previouselementsibling-javascript
Asked Answered
P

1

28

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.

Postpaid answered 23/9, 2018 at 15:45 Comment(0)
L
42

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>
Lindbergh answered 23/9, 2018 at 15:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.