Parent vs parentNode

Is there any difference between the following selectors:

var index = $(this).parent().index(); var index2 = $(this.parentNode).index(); 

From what I read, parentNode is widely supported.

Is there a reason to use one over the other?

+9
source share
2 answers

The jQuery .parent() selector selects the immediate parent of all nodes in the node set. However, since the node set in your example is just one node $(this) , there are few practical differences.

This difference matters if you have to do something like $(".foo").parent() , where there can be many nodes that have the class foo .

+9
source

parentNode is native JS, where parent () is not.

What you do in your code is to wrap the DOM elements in a jQuery object so that you can call jQuery-specific methods for it. Thus, you cannot call index () only for this.parentNode, but you can call it for $ (this.parentNode) .index () since it became a jQuery object.

Your first example wraps the current DOM element as a jQuery object, and then uses the jQuery parent () method to get its parent, and then the index of that parent. Your second example directly wraps the parent node.

+4
source

All Articles