In the last jQuery tutorial, we look into some of the tree traversing functions for parent and child elements. Today we will look into two of the simple traversing functions – first() and last().

jQuery first() function

The jQuery first() method is used to get the first element from the selected HTML elements. You can perform desired actions on the returned element.

This is the syntax for using jQuery first():

This method does not take any arguments.

jQuery first() example

Following example demonstrates the jQuery first() method usage.

jquery-first.html

In this example, there are three <p> elements in this code. The first() method returns the first span element of the first p element and changes the background color to yellow. We have used jQuery addClass() method to include the CSS style class defined in the code.

Below image shows the output produced by the above HTML page.

jQuery last() function

The jQuery last() method is used to get the last element from the selected HTML elements. You can perform desired actions on the returned element.

This is the syntax for using jQuery last():

This method does not take any arguments.

jQuery last() example

Following example demonstrates the jQuery last() method usage.

jquery-last.html

In this example, there are three <p> elements in this code. The last() method returns the last span element of the last p element and changes the background color to yellow. We have used addClass() method in jQuery to include the CSS style class defined in the code.

Below is the output produced by the above HTML page, notice the last span element background color.

jquery-last-example-450x213

That’s all for now, we will look into more jQuery traversing methods in coming posts.

By admin

Leave a Reply

%d bloggers like this: