Home >Web Front-end >JS Tutorial >Introduction to the usage of last() function
last()Function is used to get the last element among the elements matched by the current jQuery object, and return the jQuery object that encapsulates the element.
This function belongs to the jQuery object (instance).
Syntax
jQuery 1.4 Newly addedThis function.
jQueryObject.last( )
Return value
last()The return value of the function is jQuery Type that returns a jQuery object encapsulating the last matching element.
If the current jQuery object does not match any element, naturally there is no so-called last element, and an empty jQuery object will be returned.
Example & Description
The last() function and the :last selector have the following equivalent code:
$( "selector" ).last( ); //等价于 $( "selector:last" ); 以下面这段HTML代码为例: <div id="n1"> <div id="n2"> <ul id="n3"> <li id="n4" class="list">item1</li> <li id="n5" class="list">item2</li> <li id="n6">item3</li> </ul> </div> </div>
The following jQuery sample code is used to demonstrate the specifics of the last() function Usage:
//获取最后一个li元素,即n6 //先匹配所有li元素,再获取其中的最后一个 document.writeln( $("li").last().attr("id") ); // n6 //获取最后一个li.list元素,即n5 //先匹配所有的li.list元素,再获取其中的最后一个 document.writeln( $("li.list").last().attr("id") ); // n5 //获取最后一个div元素,即n2 //先匹配所有div元素,再获取其中的最后一个 document.writeln( $("div").last().attr("id") ); // n2
The above is the detailed content of Introduction to the usage of last() function. For more information, please follow other related articles on the PHP Chinese website!