Since Jquery traversing contains huge number of methods so i have decided to break the article in small small part , so it will easier to read it.
In this post we will see when to use First and Last method of Jquery traversing
First()
>> first method is used to loop in the given dom element and find out the first element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <script> $(function () { $("li").first().css("background-color", "Silver"); }); </script> </head> <body> <fieldset> <legend> Sample code for First method in Jquery </legend> <ul> <li>list item 0</li> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> </fieldset> </body> </html>
In the above example we saw that we are using first method to find out the first element of List item(li) and changing the selected item color to silver.
Last()
>> Last method is used to select the last element of dom element.
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <script src="../../Scripts/jquery.min.js"></script> <script> $(function () { $("li").last().css("background-color", "Silver"); }); </script> </head> <body> <fieldset> <legend> Sample code for last in Jquery </legend> <ul> <li>list item 0</li> <li>list item 1</li> <li>list item 2</li> <li>list item 3</li> <li>list item 4</li> <li>list item 5</li> </ul> </fieldset> </body> </html>
In the above example we saw that last method is used to select the last element of dom element.
Summary:
In the both example we saw that first method is used select the first element and Last method is used select the last element of dom element.