jQuery Selectors
One of the most powerful features of jQuery is its selectors. They let you easily find and work with HTML elements on your page.
What Are jQuery Selectors?
jQuery selectors are used to select HTML elements so you can do things with them — like hide them, change their text, or add a class. You can select elements by their:
- Tag name (like p, div, h1)
- ID (using #id)
- Class (using .class)
- Attributes (like [type="text"])
And more!
jQuery selectors are built on CSS selectors, so if you're familiar with CSS, you'll pick it up quickly. jQuery also adds some extra selectors that are unique to it.
Basic Syntax
All jQuery selectors start with a dollar sign and parentheses:
$(selector)
The jQuery Element Selector:
In jQuery, element selectors let you select HTML elements by their tag name — just like in CSS.
How It Works
To select all elements of a specific type (like paragraphs, divs, or headers), simply use the tag name inside the jQuery selector:
$("p")
This line selects all <p> (paragraph) elements on the page.
Example
Let’s look at a simple example. When a user clicks a button, all paragraph elements will be hidden:
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});
The jQuery #id Selector:
jQuery makes it super simple to select and work with individual elements using their id attribute. This is where the #id selector comes in handy.
What Is the #id Selector?
Every HTML element can have an id attribute, and that id should be unique on the page. jQuery lets you select that exact element using a # followed by the ID name.
$("#test")
This selects the element with id="test".
Example:
Let’s say you want to hide just one specific element when a user clicks a button. Here’s how you can do it:
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});
The jQuery .class Selector:
In jQuery, selecting multiple elements that share the same class is easy — thanks to the .class selector.
What Is the .class Selector?
Classes are often used in HTML to group elements that share the same styling or behavior. In jQuery, you can select these elements by writing a dot (.) followed by the class name:
$(".test")
This selects all elements that have class="test".
Example:
Let’s say you want to hide all elements with the class test when a user clicks a button. Here’s how you can do that with jQuery:
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});