Is there a difference between the following selectors:
var index = $(this).parent().index();
var index2 = $(this.parentNode).index();
From what I have read, parentNode is widely supported.
Is there a reason to use one over the other?
yeah, but unlike nextsibling text or comment nodes can't be parent. there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.
The Node.parentNode read-only property returns the parent of the specified node in the DOM tree. Syntax. parentNode is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.
To get the parent node of a specified node in the DOM tree, you use the parentNode property: let parent = node.parentNode; Code language: JavaScript (javascript) The parentNode is read-only. The Document and DocumentFragment nodes do not have a parent, therefore the parentNode will always be null.
The Node.parentNode read-only property returns the parent of the specified node in the DOM tree. parentNode is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.
The jQuery .parent()
selector selects the immediate parent of all the nodes in the node set. However, since in your example the node set is just one node $(this)
, there's little practical difference.
This difference matters if you were to do something like $(".foo").parent()
, where there might be many nodes that have the class foo
.
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