A Comprehensive Look at jQuery Selectors
This article benefited from peer review by Matt Smith and Tim Severien. Thanks to SitePoint's peer reviewers for enhancing content quality!
Selecting elements is fundamental to manipulating web pages with jQuery. Whether you're modifying content, attaching events, or performing other actions, you'll need to target the right elements first. This tutorial explores jQuery selectors, a key component of the library.
Key Concepts
- jQuery selectors are essential for targeting webpage elements for content manipulation, event attachment, and more. These selectors utilize criteria such as IDs, classes, attributes, or combinations thereof.
- jQuery provides a wide array of selectors, including basic, index-based, child, attribute, content, hierarchy, form, and visibility selectors. Each type offers unique selection capabilities based on specific conditions and parameters.
- Enhancements in jQuery 3 significantly improved the speed of custom selectors like
:visible
and:hidden
(up to 17x faster in some cases). Visibility is now determined by the presence of a layout box fromgetClientRects
. - Caching selected elements boosts performance, especially with numerous selectors. Storing selections in variables reduces redundant DOM scans.
- While many jQuery selectors mirror CSS selectors, jQuery also includes its own custom selectors for more concise and efficient element selection.
jQuery Selectors in Detail
jQuery selectors primarily identify elements based on criteria like ID, class, attributes, or combinations. Many are based on CSS selectors, but jQuery extends functionality with custom selectors.
Basic Selectors
Select elements by ID ($("#id")
), class ($(".class")
), or tag name ($("li")
). Combine these (e.g., $(".class tag")
) or use multiple selectors separated by commas (e.g., $("selectorA, selectorB, selectorC")
).
Additional basic selectors:
-
:header
: Selects all headings (<h1></h1>
to<h6></h6>
). More concise than individually listing each heading tag. -
:target
: Selects the element whose ID matches the URL fragment identifier (e.g.,https://example.com/#myElement
). -
:animated
: Selects elements currently undergoing animation (requires the jQuery effects module).
Index-Based Selectors
jQuery offers zero-based index selectors:
-
:eq(n)
: Selects the element at indexn
(supports positive and negative indices). -
:lt(n)
: Selects elements with an index less thann
. -
:gt(n)
: Selects elements with an index greater than or equal ton
. -
:first
: Selects the first matched element. -
:last
: Selects the last matched element. -
:even
: Selects elements with even indices (0, 2, 4...). -
:odd
: Selects elements with odd indices (1, 3, 5...).
Interactive demo showcasing index-based selectors
Child Selectors
These selectors target children based on index or type:
-
:first-child
: Selects the first child of each parent. -
:first-of-type
: Selects the first sibling of its type. -
:last-child
: Selects the last child of each parent. -
:last-of-type
: Selects the last sibling of its type. -
:nth-child(n)
: Selects the nth child (supports various expressions like numbers,even
,odd
, formulas). -
:nth-last-child(n)
: Similar to:nth-child
, but counts from the last child. -
:nth-of-type(n)
: Selects the nth sibling of its type. -
:nth-last-of-type(n)
: Similar to:nth-of-type
, but counts from the last sibling. -
:only-child
: Selects elements that are the only child of their parent. -
:only-of-type
: Selects elements with no siblings of the same type.
Interactive demo showcasing child selectors
Attribute Selectors
Select elements based on attribute values:
-
[attribute="value"]
: Selects elements with the exact attribute value. -
[attribute^="value"]
: Selects elements whose attribute value begins with "value". -
[attribute$="value"]
: Selects elements whose attribute value ends with "value". -
[attribute*="value"]
: Selects elements whose attribute value contains "value". -
[attribute|="value"]
: Selects elements whose attribute value is equal to or starts with "value" followed by a hyphen. -
[attribute~="value"]
: Selects elements whose attribute value contains "value" as a space-separated word. -
[attribute!="value"]
: Selects elements without the attribute or with a different value. -
[attribute]
: Selects elements with the specified attribute, regardless of value.
Content Selectors
These selectors target elements based on their content:
-
:contains(text)
: Selects elements containing the specified text (case-sensitive). -
:has(selector)
: Selects elements containing at least one element matching the provided selector. -
:empty
: Selects elements with no children. -
:parent
: Selects elements with at least one child.
Hierarchy Selectors
These selectors use the DOM hierarchy:
-
ancestor descendant
: Selects all descendants of the ancestor element. -
parent > child
: Selects direct children of the parent element. -
prev next
: Selects the next sibling of theprev
element. -
prev ~ siblings
: Selects all subsequent siblings of theprev
element.
Form Selectors
Simplified selectors for form elements:
-
:button
: Selects button elements. -
:checkbox
: Selects checkbox elements. -
:radio
: Selects radio button elements. -
:text
: Selects text input elements. -
:password
: Selects password input elements. -
:submit
: Selects submit button elements. -
:reset
: Selects reset button elements. -
:image
: Selects image button elements. -
:file
: Selects file input elements. -
:hidden
: Selects hidden form elements. -
:enabled
: Selects enabled form elements. -
:disabled
: Selects disabled form elements. -
:checked
: Selects checked checkboxes and radio buttons, and selected options. -
:selected
: Selects selected options in<select></select>
elements.
Visibility Selectors
-
:visible
: Selects visible elements. -
:hidden
: Selects hidden elements.
jQuery 3 Changes
jQuery 3 introduced performance improvements for :visible
and :hidden
, and refined the definition of visibility. Error handling for invalid selectors was also enhanced.
Caching for Performance
Caching selected elements improves performance by avoiding repeated DOM scans. Store selections in variables for reuse.
Conclusion
This tutorial comprehensively covers jQuery selectors. Remember to utilize caching for optimal performance. Understanding these selectors is crucial for effective jQuery development.
Frequently Asked Questions (FAQs)
The FAQs section from the original input is already well-structured and comprehensive. I would suggest keeping it as is, perhaps with minor wording adjustments for improved flow and clarity.
The above is the detailed content of A Comprehensive Look at jQuery Selectors. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics





Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...
