The difference between get and eq (the difference between dom object and jquery object)

After I stumbled a few times here, I decided to summarize and try not to make this most basic and low-level mistake in the future.

 

.eq() reduces the set of matching elements, and specifies the index object precisely according to the index index value.
.get() gets the corresponding DOM element by retrieving the matching jQuery object.

The same is to return elements, so what is the difference between eq and get?

eq returns a jQuery object, get returns a DOM object. for example:

$( "li" ).get( 0 ).css("color", "red"); //错误
$( "li" ).eq( 0 ).css("color", "red"); //正确

The get method essentially converts the jQuery object into a DOM object, but CSS belongs to the jQuery constructor, and this method does not exist in the DOM. If we need to use the jQuery method, we must write:

var li = $( "li" ).get( 0 );
$( li ).css("color", "red"); //用$包装

Take out the DOM object li, and then wrap it again with $ to convert it into a jQuery object before calling the css method. It is too troublesome to write in two steps, so jQuery provides us with a convenient method eq().

The implementation principle of eq() is to convert the eq method into a jQuery object in the above code:

eq: function( i ) {
    var len = this.length,
        j = +i + ( i < 0 ? len : 0 );
    return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );

The logic of the above implementation code is the same as get, the difference is that a new jQuery object is generated through pushStack.

jQuery's consideration is very thoughtful. Only a new object can be generated through the eq method, but what if a collection object is needed? So jQuery provides a slice method:

grammar:

.slice( start [, end ] )

effect:

Filters the set of matched elements according to the specified subscript range and generates a new jQuery object.

Because it is an array object, it means that we can use silce to directly get the value, so for the collection object we can write the code like this:

var arr = []
arr.push( this.slice(start[,end]) )     
this.pushStack(arr)

This this refers to the jQuery object, because the jQuery object is an array collection, so we can directly get the collection number through the native silce method, and then process it through packaging.

slice: function() {
    return this.pushStack( slice.apply( this, arguments ) );
},

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324625119&siteId=291194637