? jQuery Selectors in JavaScript
What are jQuery Selectors?
Common jQuery Selectors
1. Basic Selectors
| Selector | Description | Example |
|---|
* | Select all elements | $("*") |
element | Select all elements of type | $("p") selects all <p> |
#id | Select element by ID | $("#header") |
.class | Select elements by class | $(".active") |
2. Hierarchy Selectors
| Selector | Description | Example |
|---|
ancestor descendant | Select descendants | $("div p") selects all <p> inside <div> |
parent > child | Select direct children | $("ul > li") |
3. Attribute Selectors
| Selector | Description | Example |
|---|
[attr] | Select elements with attribute | $("[href]") selects all with href |
[attr='value'] | Select elements with attribute=value | $("[type='text']") |
[attr^='value'] | Select elements where attribute starts with value | $("[name^='user']") |
[attr$='value'] | Ends with value | $("[src$='.png']") |
[attr*='value'] | Contains value | $("[title*='hello']") |
4. Filter Selectors
| Selector | Description | Example |
|---|
:first | Select first matched element | $("li:first") |
:last | Select last matched element | $("li:last") |
:even | Even-indexed elements (0, 2, 4...) | $("tr:even") |
:odd | Odd-indexed elements | $("tr:odd") |
:not(selector) | Select elements not matching selector | $("input:not(:checked)") |
5. Form Selectors
| Selector | Description | Example |
|---|
:input | All input, textarea, select, button | $(":input") |
:text | Input elements with type="text" | $(":text") |
:checkbox | Checkbox inputs | $(":checkbox") |
:checked | Checked checkboxes/radios | $(":checked") |
Example Usage
// Select all paragraphs inside a div with class 'content'$(".content p").css("color", "blue");// Select all links that start with 'https'$("a[href^='https']").addClass("secure-link");// Select first list item and highlight it$("li:first").css("background-color", "yellow");
Summary
| Purpose | Selector Example |
|---|
| Select by ID | $("#myId") |
| Select by Class | $(".myClass") |
| Select all elements | "*" |
| Select children | $("parent > child") |
| Select attribute | $("[attr='value']") |
| Select by position | $("li:first"), $("li:odd") |
Want me to show you advanced selectors, or how to combine selectors for complex queries?
Disclaimer for AI-Generated Content:
The content provided in these tutorials is generated using artificial intelligence and is intended for educational purposes only.