:First Selector in jQuery
A useful tool for specifically focussing on particular elements on your website is jQuery’s :first selector. Among a group of matching elements, it functions as a filter to choose only the first element.
Syntax:
The usual jQuery :first selector syntax is:
$('element:first')
‘Element’ can be any HTML tag (p, div, img, li). The parentheses of the $ function encapsulate the full jQuery selector statement, including :first.
For example:
- Select the first paragraph using $(‘p:first’).
- $(‘li:first’) selects the first item.
- To choose the first image element, use $(‘img:first’).
How it Works
The purpose of the JavaScript library jQuery is to make basic web development tasks, such as HTML document traversal and manipulation, easier. With further custom extensions, its selectors are based on CSS selectors. To define or access jQuery, use the $ symbol. To “query (or find)” HTML elements, use the (selector) portion.
Using the :first selector causes jQuery to do the following actions:
Selection of a Set: The process of selecting a set begins with jQuery locating every element on the page that matches the element component of your selector (for example, all <p> or <img> tags). In doing so, an initial “matched set” of elements is produced.
Filtering: On this first matched set, the :first selector part subsequently serves as a filter. In the order that they appear in the Document Object Model (DOM), it lowers the set to just include the first member from that collection.
Action Application:This single first element will be the only object to which any further jQuery methods (such as.attr(),.addClass(), and.hide()) are applied when you chain them onto this selector. As a result, if you use $(‘div.poem-stanza’).addClass(‘highlight’), jQuery will add the class and iterate through all matched.poem-stanza divs. The set is already limited to one before the action is applied when :first is used, though, which makes it extremely particular.
With the help of this technology, you may precisely target and work with a single instance of a particular element type on a page without impacting other components that are identical.
Code Example
The retrieval of an attribute value from the first image on a webpage serves as a useful example to demonstrate the :first selector.
<!DOCTYPE html>
<html>
<head>
<title>:first Selector List Demo</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<style>
li {
padding: 5px;
margin: 4px;
background-color: #f2f2f2;
}
.highlight {
background-color: yellow;
font-weight: bold;
}
</style>
</head>
<body>
<h3>Fruits List</h3>
<ul>
<li>Apple</li>
<li>Banana</li>
<li>Mango</li>
<li>Orange</li>
</ul>
<script>
$(document).ready(function() {
// Select and highlight the first list item
$('li:first').addClass('highlight');
});
</script>
</body>
</html>
Output:
Fruits List
• Apple
• Banana
• Mango
• Orange
Explanation of the Code
HTML Structure:
The HTML creates a simple webpage. It guarantees that jQuery functions are available by including a head section with a title and a link to the jQuery library hosted on a CDN (Content Delivery Network). Additionally, a style block in the head sets some basic CSS for list items (<li>), that includes a light grey background, padding, and margin. Additionally, it specifies a highlight class that makes the font bold and the backdrop yellow.
The level 3 header “Fruits List” appears in the body section, followed by an unordered list (<ul>) with the following four list items (<li>): “Apple,” “Banana,” “Mango,” and “Orange.”
JavaScript (jQuery) Functionality:
The main jQuery logic is contained in the script block at the end of the body.
- $(document).ready(function() {… });: This common jQuery construct makes sure that the code inside it only executes when the browser has fully loaded and parsed the HTML document. By doing this, mistakes that might happen if the script attempted to work with elements that weren’t yet present in the DOM are avoided.
- The crucial section that makes use of the jQuery :first selection is $(‘li:first’).
- At first, $(‘li’) chooses every <li> element in the document.
- This set is then filtered by the :first selector, which reduces it to only the first <li> element that appears in the document’s structure. It will pick the <li>Apple</li> element in this particular HTML.
- .addClass(‘highlight’): This jQuery method applies the CSS class highlight to the first list item after it has been selected. This will make the text of “Apple” bold and alter its background colour to yellow, as specified in the <style> block.
In conclusion, the jQuery script waits for the content to be ready before locating the first list item in the entire document and applying the “highlight” styling to it. This process visually highlights “Apple” on the “Fruits List” when the page loads.