Selectors are the foundation of everything you do in jQuery. They allow you to "pick" or "select" the HTML elements you want to work with. If you are already familiar with CSS selectors, you are 90% of the way there because jQuery uses almost the exact same syntax.
In jQuery, you use the $() function to select elements. Inside the
parentheses, you place a string that tells jQuery what to look for. Once an element is
selected, you can immediately chain an action to it.
$( "your-selector-here" ).action();
These are the selectors you will use most often in your daily development.
$("p")
Selects all <p> elements on the page.
$("#header")
Selects the single element with id="header".
$(".btn")
Selects all elements with class="btn".
You can target elements based on their HTML attributes, such as href,
src, or type.
| Selector | Description |
|---|---|
$("[href]") |
Selects all elements with an href attribute. |
$("a[target='_blank']") |
Selects all links that open in a new window. |
$("input[type='text']") |
Selects all text input fields in a form. |
jQuery provides several custom "pseudo-selectors" that make it incredibly easy to target specific elements in a list.
// Selects the first element
$("p:first").css("color", "red");
// Selects the last
element
$("li:last").addClass("active");
// Selects all even numbered table rows
$("tr:even").css("background", "#eee");
// Selects all odd numbered list items
$("li:odd").fadeOut();
Here is a handy reference table of the most common selectors you'll need:
| Syntax | Description |
|---|---|
$("*") |
Selects every single element on the page. |
$(this) |
Selects the current HTML element being interacted with. |
$("p.intro") |
Selects all <p> elements with class="intro". |
$("ul li:first") |
Selects the first <li> of the first <ul>. |
$(":button") |
Selects all <button> elements and input elements of type button. |
$("tr:even") |
Selects all even table rows (2nd, 4th, etc.). |
$("tr:odd") |
Selects all odd table rows (1st, 3rd, etc.). |
Imagine you have a simple list. With one line of jQuery, we can target specific items based on their position.
<ul id="demoList">
<li>Item 1 (Odd)</li>
<li>Item 2 (Even)</li>
<li>Item 3 (Odd)</li>
<li>Item 4 (Even)</li>
</ul>
:even and :odd selectors are 0-indexed. This
means the first item is 0 (even), the second is 1 (odd), and so on.
Requires different methods for different targets:
getElementById()getElementsByClassName()querySelectorAll()One function to rule them all:
$() handles everything.#id for a specific element (IDs should be unique)..class for multiple elements with the same styling or behavior.
$() selector returns a collections of elements even if only one is
found.$("div p span").