Introduction
In jQuery, selection methods allow us to filter and refine elements efficiently. Five essential methods that help manipulate element selections are:
first()
last()
eq()
filter()
not()
These methods provide precise control over DOM elements, making your code cleaner and more effective. Let’s explore each method with examples.
1. jQuery
first() Method
Definition:
The first()
method selects only the first element from a matched set.
Syntax:
$(selector).first();
Example:
<!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> </head> <body> <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <button id="btn">Highlight First Item</button> <script> $(document).ready(function(){ $("#btn").click(function(){ $("li").first().css("color", "red"); }); }); </script> </body> </html>
2. jQuery
last() Method
Definition:
The last()
method selects only the last element from a matched set.
Syntax:
$(selector).last();
Example:
$("li").last().css("color", "blue");
Explanation:
- This method targets the last
<li>
element and changes its color to blue.
3. jQuery
eq() Method
Definition:
The eq(n)
method selects the element at index n
from a matched set. Indexing starts from 0.
Syntax:
$(selector).last();
Explanation:
- This method targets the last
<li>
element and changes its color to blue.
3. jQuery
eq() Method
Definition:
The eq(n)
method selects the element at index n
from a matched set. Indexing starts from 0.
Syntax:
$(selector).eq(index);
$("li").eq(1).css("font-weight", "bold");
4. jQuery
filter() Method
Definition:
The filter(selector/function)
method filters elements based on a selector or function.
Syntax:
$(selector).filter(criteria);
Example:
$("li").filter(":even").css("background-color", "lightgray");
Explanation:
- Selects and applies a background color to even-indexed
<li>
elements.
5. jQuery
not() Method
Definition:
The not(selector/function)
method removes elements that match a specified condition.
Syntax:
$(selector).not(criteria);
Example:
$("li").not(":first").css("text-decoration", "underline");
Explanation:
- All
<li>
elements except the first one will have underlined text.
Conclusion
These five jQuery methods—first()
, last()
, eq()
, filter()
, and not()
—help in efficiently selecting and manipulating elements in a webpage. By mastering these, you can refine your jQuery-based scripts for better performance and readability.