Hardware FixRecommendedDevice not working? Your driver may be the problemCheck updates for common hardware issues.Fix DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix Now×
Skip to content
World desk4 min

CSS Selectors: How to Find and Target Elements

A practical guide to CSS selector syntax, relationships, pseudo-classes, and using querySelector() or querySelectorAll() to find elements in JavaScript.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

CSS selectors are patterns that match elements in a document. Use them in stylesheets to target elements for styling, or pass them to JavaScript’s querySelector() and querySelectorAll() methods to find elements in the DOM.

Choose a selector that describes what you need

Begin with an element’s type, class, ID, or attributes. Add more conditions or relationships only when they help distinguish the target.

What to match Selector form Example
Elements of a particular type Type selector button
Any element Universal selector *
An element with a class Class selector .notice
An element with an ID ID selector #main
An element with an attribute or attribute value Attribute selector input[type="email"]
One element meeting several conditions Compound selector button.primary[disabled]
A state or structural condition Pseudo-class input:focus, li:first-child
A stylable part of an element Pseudo-element p::first-line
Elements matching any of several selectors Selector list h1, h2

These selector forms are described in the W3C Selectors Level 4 specification and MDN’s CSS selectors reference.

Combine selectors to express relationships

Conditions written together without a combinator apply to the same element: button.primary[disabled] matches a button that has the primary class and the disabled attribute. A combinator connects different parts of the document structure.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Relationship Combinator Example Meaning
Descendant Whitespace article p A paragraph anywhere inside an article
Direct child > ul > li A list item whose parent is a list
Immediately following sibling + h2 + p A paragraph immediately after a heading, with the same parent
Later sibling ~ h2 ~ p A paragraph later than a heading, with the same parent

A comma means “match either selector,” not “match both conditions on one element.” For example, h1, h2 selects headings of either type. A compound selector such as h1.title instead requires one element to satisfy both conditions.

Use selectors in JavaScript to retrieve elements

Use querySelector() when you need the first matching element, and querySelectorAll() when you need all matches. An element-scoped query searches that element’s descendants.

Rank #2
Sale
HTML and CSS: Design and Build Websites
  • HTML CSS Design and Build Web Sites
  • Comes with secure packaging
  • It can be a gift option
const firstButton = document.querySelector("button.primary");
const allButtons = document.querySelectorAll("button");
const panel = document.querySelector("#panel");
const nestedLink = panel?.querySelector("a[href]");

querySelector() returns the first matching Element, or null if there is no match. querySelectorAll() returns the matching elements as a collection. The optional chaining in the example prevents an error if no panel is found; without it, calling querySelector() on null would fail. See MDN’s Document.querySelector() reference and MDN’s Element.querySelector() reference.

Escape dynamic IDs and class names

HTML permits ID and class values that are not valid CSS identifiers. If a value comes from data and may contain punctuation or other special characters, escape it before inserting it into a selector. Keep the selector structure fixed rather than concatenating arbitrary untrusted text as selector syntax.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
const id = "item:42";
const element = document.querySelector(`#${CSS.escape(id)}`);

If a selector string is invalid, the query method throws a SyntaxError rather than returning null. Refer to the MDN CSS.escape() reference when building selectors from dynamic values.

Know what selectors do—and do not—return

  • Pseudo-class versus pseudo-element: A pseudo-class adds a matching condition, often based on state or structure. A pseudo-element describes a stylable part. Use the modern double-colon form, as in ::first-line; a few legacy pseudo-elements also support single-colon notation for compatibility.
  • Pseudo-elements are not DOM elements: A stylesheet can target p::first-line, but querySelector() does not return a pseudo-element as an Element.
  • Duplicate IDs: IDs should be unique in well-formed markup. If duplicates exist, a first-match query for that ID returns only the first match in document order.
  • Stylesheet specificity: If cascade conflicts matter, note that :is() takes the specificity of its most specific argument, while :where() contributes zero specificity. Consult the W3C specification for the relevant selector rules.

Check support for newer selector features

The W3C document identifies Selectors Level 4 as a Working Draft dated 22 January 2026; a specification describes syntax, not guaranteed support in every browser, automation tool, or embedded environment. MDN describes querySelector() as widely available across browsers since July 2015, but that does not establish support for every newer selector feature. Check compatibility for the specific selector and target environments your project uses.

Rank #4
Sale
Web Design with HTML, CSS, JavaScript and jQuery Set
  • Brand: Wiley
  • Set of 2 Volumes
  • A handy two-book set that uniquely combines related technologies Highly visual format and accessible language makes these books highly effective learning tools Perfect for beginning web designers and front-end developers
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Or skip the browser setup

If you are trying to inspect a page visually rather than write a selector query against its DOM, ScreenshotNeo can return a screenshot or PDF through one GET request. Its browser capture can accept consent banners and remove more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers report the page verdict and billing status. ScreenshotNeo also provides an MCP server with screenshot, page-info, and PDF tools for AI agents.

Example request (replace YOUR_API_KEY with your key):

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. The Free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 screenshots. Sign up for the free plan.

Frequently Asked Questions

Can a CSS selector match more than one element?

Yes. A selector can match multiple elements; use JavaScript’s querySelectorAll() when you need all of them.

Does querySelector() return an empty result when no element matches?

No. It returns null when there is no match. An invalid selector instead throws a SyntaxError.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. Shenzhen desk3 min
    HONOR Expands Beyond Smartphones With Humanoid Robot RevealHONOR said it unveiled its first humanoid robot at MWC 2026 and named shopping assistance, workplace inspections, and supportive companionship as intended uses. Later Robotics D1 claims and a reported…
  2. Cupertino desk5 min
    Apple Unveils AirPods Max 2: The Upgrade That Should Have Happened Years AgoAirPods Max 2 adds H2-powered audio features and Apple claims up to 1.5× more effective ANC, but its design, Smart Case, and 20-hour battery rating are unchanged. Wired lossless audio…
  3. Cupertino desk4 min
    Apple’s OLED Touch MacBooks Are Coming—but the Dynamic Island Is the Real GambleApple has not announced an OLED touchscreen MacBook, but reports point to high-end models arriving in late 2026 or early 2027. The reported Mac Dynamic Island could be useful, but…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.