Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between previoussibling and previouselementsibling-javascript

Tags:

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.

like image 534
QMaster Avatar asked Sep 23 '18 15:09

QMaster


People also ask

How do I find an old sibling element?

You can use previousElementSibling to get the previous element node (skipping text nodes and any other non-element nodes). To navigate the opposite way through the child nodes list use Node. nextSibling.

Which of the following properties returns the previous node of the specified node in the same tree level?

The previousSibling property returns the previous node on the same tree level. The previousSibling property returns a node object.


1 Answers

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>
like image 68
NullPointer Avatar answered Sep 21 '22 18:09

NullPointer