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.
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.
The previousSibling property returns the previous node on the same tree level. The previousSibling property returns a node object.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With