ArticleZip > Select First And Last Element With Particular Class Using Jquery

Select First And Last Element With Particular Class Using Jquery

If you're a coder who's ever found yourself needing to manipulate the first and last elements of a specific class using jQuery, you're in the right place. jQuery is a powerful JavaScript library that simplifies DOM manipulation. In this article, we'll guide you through selecting the first and last element with a particular class using jQuery.

To start, let's create a simple HTML structure with a few elements having the same class. For this demonstration, let's use a class called "example-class."

Html

<div class="example-class">Element 1</div>
<div class="example-class">Element 2</div>
<div class="example-class">Element 3</div>
<div class="example-class">Element 4</div>

Now, to select the first element of this class, you can utilize the jQuery selector `:first`. This selector helps you target the first occurrence of the specified class. You can achieve this by using the following jQuery code:

Javascript

$(".example-class:first").css("color", "red");

In this code snippet, we are selecting the first element with the class "example-class" and changing its text color to red. You can modify this code to perform any desired action on the selected element.

On the other hand, if you want to target the last element with the class "example-class," you can employ the jQuery selector `:last`. Here's how you can do it:

Javascript

$(".example-class:last").css("font-weight", "bold");

In this code snippet, we are selecting the last element with the class "example-class" and setting its font weight to bold. Similar to selecting the first element, you can customize this code to suit your specific requirements.

Additionally, if you wish to select both the first and last elements of the class "example-class" simultaneously, you can utilize the `:first` and `:last` selectors in conjunction. Here's an example:

Javascript

$(".example-class:first, .example-class:last").css("background-color", "yellow");

In this code snippet, we are selecting both the first and last elements with the class "example-class" and giving them a yellow background color. This demonstrates how you can apply styles or perform actions on multiple selected elements within the same line of code.

Understanding how to select the first and last elements of a particular class using jQuery provides you with the flexibility to manipulate elements efficiently in your web development projects. By following these simple guidelines and examples, you can enhance your coding skills and create dynamic and interactive web experiences effortlessly.

×