eq(), first() and last() JQuery functions

In this post of JQuery, I will explain the three functions eq(), first(), and last() functions with a example.

Below is the complete code for reference


1  <html>
2   <head>
3       https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
4   </head>
5   <body>
6       
7           function selectElement() {
8               var $elements = $('a');
9                       
10              var $indexedElement = $elements.eq(0);
11              alert($indexedElement.length);
12              
13              var $firstElement = $elements.first();
14              alert($firstElement.length);
15              
16              var $lastElement = $elements.last();
17              alert($lastElement.length);
18          }
19      
20      <input id="Button" name="Button" type="button" value="Button" onclick="selectElement();"/>
21      <br>
22      <br>
23      <a id="google" href="http://www.google.com">Google</a><br>
24      <a id="yahoo" href="http://www.yahoo.com">Yahoo</a><br>
25      <a id="rediff" href="http://www.rediff.com">Rediff</a><br>
26      <a id="msn" href="http://www.msn.com">MSN</a><br>
27  </body>
28 </html>

The method eq() as shown at line 10, operates on a collection (source), takes index (an integer representing position in the source collection) as an argument and returns another new collection containing an element exist at the specified index in the source collection. If the source collection is empty, then the new collection is also empty. A negative index can also be specified to select the elements starting from the end of the source collection.

The method first() as shown at line 13, operates on a collection (source) and returns another new collection containing the first element in the source collection. If the source collection is empty, then the new collection is also empty.

The method last() as shown at line 16, operates on a collection (source) and returns another new collection containing the last element in the source collection. If the source collection is empty, then the new collection is also empty.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s