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











Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.
