This post is about to explain a very simple trick using jQuery. This tutorial really helps you in time when you need to get the first value of list-item or last list-item.
jQuery is a brilliant way of handling DOM elements, we are going to see one of them today.
This tutorial not only teaches you how to get the first and last value of list-item, also teaches how you can get the first and last value of select option (drop-down).
Lets go to the tutorial part, First start with the HTML element:
1 2 3 4 5 |
<ul id="fruits"> <li>Apple</li> <li>Orange</li> <li>Pineapple</li> </ul> |
So, there are three list-items in the above shown example. Lets see how you can take the first list-item value from it.
jQuery Part (get the first list-item):
1 |
$("#fruits li:first-child").text(); |
So, Basically :first-child is the selector you can use to select the first element.
Similar to get the last list-item is :last-child. Lets see how you can write in jQuery:
1 |
$("#fruits li:last-child").text(); |
Also, its similar for Drop Down too:
1 2 3 4 5 6 7 |
<!-- Drop Down --> <select id="myselect"> <option>Radio</option> <option>TV</option> <option>Fridge</option> <option>Blender</option> </select> |
To get the first option value through jQuery:
1 |
$("#myselect option:first-child").text() |
To get the last option value through jQuery:
1 |
$("#myselect option:last-child").text() |
Here is an example code snippet where you can play around with it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Get First and Last Element of li and option</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script> $(function() { //list-items example alert($("#fruits li:first-child").text()); alert($("#fruits li:last-child").text()); //drop down example alert($("#myselect option:first-child").text()); alert($("#myselect option:last-child").text()); }); </script> </head> <body> <!-- list items --> <ul id="fruits"> <li>Apple</li> <li>Orange</li> <li>Pineapple</li> </ul> <!-- Drop Down --> <select id="myselect"> <option>Radio</option> <option>TV</option> <option>Fridge</option> <option>Blender</option> </select> </body> </html> |
Examples are the best way to learn anything quickly and easily. Enjoy the day!