jQuery selectors are a powerful way to find and manipulate HTML elements. They use a CSS-like syntax, making it easy to select elements by their tag name, ID, class, attributes, and more.
1. The *
Selector (Universal Selector):
Selects all elements in the DOM.
$("*").action();
Example:
$("button").click(function(){ $("*").css("border", "1px solid red"); });
2. The #id
Selector:
Selects a single element with a specific ID.
$("#myId").action();
Example:
$("#myId").text("This is the new text for the element with ID 'myId'.");
3. The .class
Selector:
Selects all elements with a specific class.
$(".myClass").action();
Example:
$(".myClass").css("color", "blue");
4. The element
Selector:
Selects all elements of a given type (tag name).
$("p").action();
Example:
$("p").hide();
5. The element, element
Selector (Group Selector):
Selects all specified elements.
$("h1, h2, p").action();
Example:
$("h1, h2, p").css("background-color", "yellow");
6. The :first
Selector:
Selects the first matched element.
$("p:first").action();
Example:
$("p:first").css("font-weight", "bold");
7. The :last
Selector:
Selects the last matched element.
$("p:last").action();
Example:
$("p:last").css("font-style", "italic");
8. The :even
Selector:
Selects even-indexed elements (index starts at 0).
$("tr:even").action();
Example:
$("tr:even").css("background-color", "lightgray");
9. The :odd
Selector:
Selects odd-indexed elements.
$("tr:odd").action();
Example:
$("tr:odd").css("background-color", "lightblue");
10. The :not(selector)
Selector:
Selects all elements that do not match the given selector.
$("p:not(.exclude)").action();
Example:
$("p:not(.exclude)").css("color", "green");
11. The :eq(index)
Selector:
Selects the element with a specific index.
$("li:eq(2)").action();
Example:
$("li:eq(2)").css("color", "red");
12. The :lt(index)
Selector:
Selects all elements with an index less than the specified number
$("li:lt(3)").action();
Example:
$("li:lt(3)").css("font-size", "20px");
13. The :gt(index)
Selector:
Selects all elements with an index greater than the specified number.
$("li:gt(3)").action();
Example:
$("li:gt(3)").hide();
14. The :header
Selector:
Selects all header elements (<h1>
to <h6>
).
$(":header").action();
Example:
$(":header").css("font-family", "Arial");
15. The :contains(text)
Selector:
Selects elements that contain the specified text.
$("p:contains('jQuery')").action();
Example:
$("p:contains('jQuery')").css("background-color", "yellow");
Chaining Selectors:
jQuery allows chaining multiple selectors and methods for concise and readable code.
$("#myId").css("color", "blue").slideUp(2000).slideDown(2000);
Using Selectors in Practice:
Selectors are the foundation of jQuery, enabling you to select specific elements and apply various methods to them.