jQuery Selectors

jQuery Selectors

jQuery Selectors — Complete Guide with Examples | TipsInLearning
jQuery Lesson

jQuery Selectors

Master all jQuery selector types — element, ID, class, attribute, filter, position, form, and visibility selectors — with a complete reference table and real code examples.

14 min read
Beginner
jQuery Basics
Free Course
What You'll Learn in This Lesson
Element, ID, and class selectors
Combining and multiple selectors
Descendant and child selectors
Attribute selectors with operators
Position and filter selectors
Form and visibility selectors

What are jQuery Selectors?

A jQuery selector is a pattern that finds and selects HTML elements on your page. Every jQuery statement starts with a selector — it tells jQuery which elements to work with before applying any action.

jQuery uses the exact same CSS selector syntax you already know from styling websites. This means you can target elements by their tag name, id, class, attributes, position in the page, or their current state.

Element
$("p")
ID
$("#myId")
Class
$(".myClass")
[ ]
Attribute
$("[href]")
Filter
$("p:first")
Visibility
$(":hidden")

Element Selector

The element selector targets all HTML elements of a specific tag type. It selects every matching element on the entire page.

jQuery — Element Selectors
// Select ALL paragraphs on the page
$("p").hide();

// Select ALL divs
$("div").css("color", "blue");

// Select EVERY element on the page
$("*").css("box-sizing", "border-box");

ID Selector

The ID selector uses a # prefix to find the one unique element with that id attribute. It is also the fastest selector in jQuery.

jQuery — ID Selector
// Select element with id="myButton"
$("#myButton").click(function() {
  alert("Clicked!");
});

// Hide element with id="content"
$("#content").hide();
Performance tip: Always prefer ID selectors when you need one specific element. The browser has a native getElementById method that is highly optimized.

Class Selector

The class selector uses a . prefix to select all elements that have a specific class name. Multiple elements can share the same class.

jQuery — Class Selector
// Select ALL elements with class="highlight"
$(".highlight").css("background-color", "yellow");

// Select ALL paragraphs with class="intro"
$(".intro").css("font-size", "18px");

Combining Selectors

You can combine selectors to be more specific about exactly which elements you want to match.

jQuery — Combined Selectors
// Only paragraphs with class "intro"
$("p.intro")

// Multiple different selectors — comma separated
$("h1, h2, h3").css("color", "navy");

// Mix of ID, class, and element
$("#myId, .myClass, p").hide();

Descendant & Child Selectors

These selectors find elements based on their relationship to other elements in the HTML structure.

SelectorFindsExample
parent childAll descendants at any depth$("#nav a")
parent > childDirect children only$("#list > li")
el + elImmediately adjacent sibling$("h2 + p")
el ~ elAll following siblings$("h1 ~ p")
jQuery — Descendant Selectors
// All links inside the nav
$("#nav a").css("color", "white");

// Only DIRECT paragraph children of #myDiv
$("#myDiv > p")

// The paragraph immediately after h2
$("h2 + p").addClass("intro");

Attribute Selectors

Attribute selectors find elements based on the presence or value of their HTML attributes.

SelectorMatches when attribute...Example
[attribute]Exists at all$("[href]")
[attr='val']Equals exact value$("[type='text']")
[attr*='val']Contains value anywhere$("[href*='google']")
[attr^='val']Starts with value$("[href^='https']")
[attr$='val']Ends with value$("[href$='.pdf']")
jQuery — Attribute Selectors
// All inputs where type equals "text"
$("[type='text']").css("border", "1px solid blue");

// All links containing "google" in href
$("[href*='google']").addClass("external");

// All PDF links
$("[href$='.pdf']").addClass("pdf-link");

Filter Selectors — Position Based

Filter selectors are unique to jQuery — not part of standard CSS. They select elements based on their position using a colon prefix.

SelectorSelectsExample
:firstFirst matched element$("p:first")
:lastLast matched element$("li:last")
:evenEven-indexed (0, 2, 4...)$("tr:even")
:oddOdd-indexed (1, 3, 5...)$("tr:odd")
:eq(n)Element at index n$("p:eq(2)")
:gt(n)Elements with index > n$("p:gt(2)")
:lt(n)Elements with index < n$("p:lt(3)")
jQuery — Filter Selectors
// Zebra stripe a table
$("tr:even").css("background", "#f0f0f0");
$("tr:odd").css("background", "#ffffff");

// Third paragraph (index 2)
$("p:eq(2)").addClass("active");

Form Selectors

jQuery provides special selectors for targeting form elements by their type or state:

SelectorSelects
:checkedChecked checkboxes or radio buttons
:selectedSelected dropdown options
:disabledDisabled form elements
:enabledEnabled form elements
:textText input fields
:checkboxCheckbox inputs
:radioRadio button inputs
:inputAll form elements
jQuery — Form Selectors
// Get all checked checkboxes
$("input:checked").each(function() {
  console.log($(this).val());
});

// Disable all form inputs
$(":input").prop("disabled", true);

Visibility Selectors

Select elements based on whether they are currently visible or hidden:

jQuery — Visibility Selectors
// Select all VISIBLE paragraphs
$("p:visible").css("color", "green");

// Show all HIDDEN elements
$(":hidden").show();

// Count hidden elements
const count = $(":hidden").length;

Selector Performance Tips

Not all selectors perform equally. Here is how to write faster selectors:

Fast ✅Slower ⚠️Why
$("#id")$(".class")ID uses native getElementById
$("div.class")$(".class")Tag name narrows scope
$("#id").find("p")$("#id p")find() is optimized
const $el = $(".item")Repeat $(".item")Cache once, reuse many times
jQuery — Performance Best Practices
// Cache selectors you use more than once
const $items = $(".item");
$items.hide();
$items.fadeIn();

// Use find() for scoped search
$("#container").find("p").hide();

// Check if selector matched anything
if ($("#myElement").length > 0) {
  $("#myElement").show();
}

Try It Yourself

Challenge — jQuery Selector Practice
1Use $("p") to hide all paragraphs, then use $("#myBtn") to show them on click
2Use $(".highlight") to change background color to yellow
3Use $("tr:even") and $("tr:odd") to create zebra-striped table rows
4Use $("[href^='https']") to add a class to all secure links
5Use $("input:checked") to loop through checked checkboxes and alert their values
Lesson Summary — Key Takeaways
1$("p") element, $("#id") ID, $(".class") class — the three core selectors
2ID selectors are the fastest — use them when targeting a single element
3Attribute selectors use square brackets with operators like ^= *= $=
4Filter selectors like :first :even :eq(n) are unique to jQuery
5Form selectors like :checked :disabled target form elements by state
6Cache selectors and use .find() for better performance

Frequently Asked Questions

Common questions beginners ask about jQuery selectors:

jQuery selectors are patterns used to find and select HTML elements on a page. They use the same CSS selector syntax you already know. You can target elements by tag name, id, class, attributes, position, or current state. Every jQuery statement starts with a selector inside the $() function.

The element selector selects all HTML elements of that tag type. The ID selector using a # prefix selects exactly one element with that unique id. The class selector using a . prefix selects all elements sharing that class name. ID selectors are fastest because each id is unique and browsers use optimized native methods to find them.

Use attribute selectors inside square brackets. [attribute] selects elements that have that attribute. [attr='val'] selects where it equals an exact value. [attr*='val'] selects where it contains the value anywhere. [attr^='val'] selects where it starts with the value. [attr$='val'] selects where it ends with the value.

Filter selectors are special jQuery selectors not found in standard CSS. They use a colon prefix to refine selections by position or state — :first, :last, :even, :odd, :eq(n). They are especially useful for styling tables with alternating row colors or targeting specific items in a list.

The ID selector is the fastest because browsers have a native getElementById method that is highly optimized. Always use ID selectors for single elements. For class selectors, narrow the scope by adding the tag name first — $("div.myClass") is faster than $(".myClass"). Cache selectors in variables when you need to use the same selector multiple times.

Post a Comment