Get first element using first() method in jQuery in Tamil


In jQuery, the first() method is used to select the first element in the set of matched elements. This method allows you to narrow down your selection to only the first element that matches your initial selector. It's particularly useful when you are working with a collection of elements and you want to operate on or retrieve data from only the first one.



first() Method

The first() method in jQuery is used to reduce the set of matched elements to the first one.

$(selector).first()

selector : A string containing a selector expression to match the elements against.

  • The first() method can be applied to any set of elements, not just lists. It selects the first element from the set of matched elements.
  • If the set of matched elements is empty, first() will return an empty jQuery object.
  • It's an efficient way to operate on or retrieve data from the first element in a collection without manipulating the entire set.
  • The first() method allows you to work with or manipulate the first element in a set of matched elements, providing a convenient way to target specific elements within your jQuery selections.

Source Code

  • $('ul.list').children('li').first().addClass('color'); selects the immediate children (<li>) of the unordered list with the class 'list', then applies the first() method to select the first element from this set. Finally, it adds the class 'color' to the first <li> element.
  • Alternatively, the commented out line //$('ul.list').children('li:first-child').addClass('color'); achieves the same result but uses the :first-child pseudo-class selector instead of the first() method.
  • The jQuery code will add the class 'color' to the first <li> element among the immediate children of the unordered list with the class 'list'. As a result, the text color of the first list item ("Graphic Designing") will be changed to red.
<html>
	<head>
		<title>DOM Query</title>
		<style>
			li{color:black;}
			.color{color:red;}
		</style>
	</head>
	<body>
	<h3>First Child</h3>
	<ul class='list'>
		<li>Graphic Designing</li>
		<li>Web Designing</li>
		<li>Programming</li>
		<li>
			<ul>
				<li>C Program</li>
				<li>C++ Program</li>
				<li>Java</li>
				<li>C#</li>
			</ul>
		</li>
	</ul>
	<script src="js/jquery.js"></script>
		<script>
			$("document").ready(function(){
				//$('ul.list').children('li:first-child').addClass('color');
				$('ul.list').children('li').first().addClass('color');
			});
		</script>
	</body>
</html>