Basic Selectors
Select elements by tag name, id, and class — just like CSS.
Syntax
$("tag"), $("#id"), $(".class")jQuery selectors use the same syntax as CSS. The three you will use most:
| Selector | Selects |
|---|---|
$("p") | all <p> elements |
$("#id") | the element with that id |
$(".class") | all elements with that class |
$("*") | every element |
You can combine them: $("ul li.active") selects li elements with class active inside a ul.
Example
Loading editor…
Press Run to see the result.
When to use it
- A blog highlights all <h2> headings by selecting them with $("h2") and applying a custom color.
- A dashboard hides a specific panel using $("#analyticsPanel").hide() for users without permission.
- A stylesheet switcher adds a .dark-mode class to all .card elements via $(".card").addClass("dark-mode").
More examples
Select all paragraphs by tag
The tag selector matches every <p> on the page and applies a font-size in one call.
<p>First paragraph.</p>
<p>Second paragraph.</p>
<script>
$(function () {
$("p").css("font-size", "18px");
});
</script>Select unique element by id
The # prefix targets the unique #hero element and passes a style object to .css().
<div id="hero">Welcome!</div>
<script>
$(function () {
$("#hero").css({
background: "#1a1a2e",
color: "#eee",
padding: "20px"
});
});
</script>Select multiple classes at once
The class selector $(".btn") matches both buttons; one click handler covers the entire group.
<button class="btn primary">Save</button>
<button class="btn secondary">Cancel</button>
<script>
$(function () {
$(".btn").on("click", function () {
$(this).prop("disabled", true);
});
});
</script>
Discussion