Get First and Last Element in jQuery in Tamil


In jQuery, you can use the :first and :last selectors to target the first and last elements of a matched set, respectively. These selectors are useful when you want to apply specific actions or styles to only the initial or final element within a set of matched elements.



:first Selector:

The :first selector targets the first element of a matched set. It is often used to select and manipulate the initial element in a collection.

:last Selector:

The :last selector targets the last element of a matched set. It is useful when you want to specifically interact with the final element in a group.

Combining Selectors:

You can also combine :first and :last selectors with other selectors to create more specific queries.

Source Code

This HTML and jQuery code demonstrates the use of the :first and :last selectors to target and apply different styles to the first and last elements with the class "a" in the provided HTML document. Let's break down the code

  • The code selects the first element with the class "a" using $('.a:first') and applies a red background color to it using .css('background-color', 'red').
  • It selects the last element with the class "a" using $('.a:last') and applies an orange background color to it using .css('background-color', 'orange').
  • The first element with the class "a" will have a red background, and the last element with the class "a" will have an orange background.

This demonstrates how the :first and :last selectors in jQuery can be used to style specific elements within a set based on their position in the document.

<html>
	<head>
		<title>First and Last Element Selector</title>
	</head>
	<body>
		<h1>Tutor Joes</h1>
		<i class="a">Computer Education</i> 
		<p id="b">Learn More Be Smart</p>
		<i class="a">Computer Education</i> 
		<i class="a">Computer Education</i> 
		<i class="a">Computer Education</i>
		<script src="js/jquery.js"></script>
		<script>
			$("document").ready(function(){
				$('.a:first').css('background-color','red');
                                $('.a:last').css('background-color','orange');
			});
		</script>
	</body>
</html>

In summary, the :first and :last selectors in jQuery provide a convenient way to target and manipulate the first and last elements in a set, respectively, making it easy to apply specific actions to these elements within a collection.