CSS
Web Development
HTML
Programming
Coding

Is there a CSS selector for text content? (select elements by text)

Codemia Knowledge Hub ·

No, standard CSS does not have a selector that matches elements based on their text content. Selectors work on DOM structure (element names, classes, IDs, attributes, and relationships between elements) and cannot inspect text nodes. To style elements by the text they contain, add semantic markup (classes or data attributes) or use JavaScript to inspect the text and apply classes.

Why CSS cannot select by text

CSS is a declarative styling language, not a DOM query language. The selector specification matches on structural properties of elements:

CSS Can MatchCSS Cannot Match
Element type (div, p, span)Text content of an element
Class names (.warning)Substring of inner text
IDs (#header)Text of child text nodes
Attributes ([data-status])Computed text from pseudo-elements
Pseudo-classes (:hover, :focus, :checked)Text generated by JavaScript
Structural position (:first-child, :nth-of-type)Dynamic content changes
Parent-child relationships (article > p)Text across nested elements

This boundary is deliberate. Text matching would force the CSS engine to parse and compare strings during layout, which is expensive and blurs the line between styling and application logic.

Encode the meaning in classes or data attributes

To style elements by their meaning, put that meaning in the markup. Classes and data attributes are the most reliable options.

Using classes

html
1<ul class="message-list">
2  <li class="message message-warning">Disk space low</li>
3  <li class="message message-success">Backup completed</li>
4  <li class="message message-error">Connection failed</li>
5</ul>
css
1.message-warning {
2  color: #b45309;
3  background-color: #fef3c7;
4}
5
6.message-success {
7  color: #15803d;
8  background-color: #dcfce7;
9}
10
11.message-error {
12  color: #dc2626;
13  background-color: #fee2e2;
14}

Using data attributes

When the condition maps to a value rather than a boolean category, data attributes are cleaner:

html
<div data-status="warning">Disk space low</div>
<div data-status="success">Backup completed</div>
<div data-status="error">Connection failed</div>
css
1[data-status="warning"] {
2  color: #b45309;
3  border-left: 4px solid #f59e0b;
4}
5
6[data-status="success"] {
7  color: #15803d;
8  border-left: 4px solid #22c55e;
9}
10
11[data-status="error"] {
12  color: #dc2626;
13  border-left: 4px solid #ef4444;
14}

Data attributes also support partial matching:

css
1/* Matches any element where data-status starts with "warn" */
2[data-status^="warn"] {
3  color: #b45309;
4}
5
6/* Matches any element where data-status contains "err" */
7[data-status*="err"] {
8  color: #dc2626;
9}
10
11/* Matches any element where data-status ends with "cess" */
12[data-status$="cess"] {
13  color: #15803d;
14}

These attribute selectors are native CSS and work in all browsers. They match attribute values, not text content.

Matching text with JavaScript

If you must style by text content and cannot change the markup (third-party widgets, CMS output, legacy systems), use JavaScript.

Vanilla JavaScript

javascript
1// Add a class based on text content
2document.querySelectorAll('.log-entry').forEach(entry => {
3  const text = entry.textContent;
4  if (text.includes('ERROR')) {
5    entry.classList.add('log-error');
6  } else if (text.includes('WARN')) {
7    entry.classList.add('log-warning');
8  }
9});
css
1.log-error {
2  color: #dc2626;
3  font-weight: bold;
4}
5
6.log-warning {
7  color: #b45309;
8}

MutationObserver for content added later

If the DOM changes after load (e.g., streaming log output), use a MutationObserver to apply classes as new elements appear:

javascript
1const observer = new MutationObserver(mutations => {
2  for (const mutation of mutations) {
3    for (const node of mutation.addedNodes) {
4      if (node.nodeType === Node.ELEMENT_NODE && node.classList.contains('log-entry')) {
5        if (node.textContent.includes('ERROR')) {
6          node.classList.add('log-error');
7        }
8      }
9    }
10  }
11});
12
13observer.observe(document.querySelector('.log-container'), {
14  childList: true,
15  subtree: true
16});

Text inspection stays in JavaScript, and CSS handles only the visual styling.

jQuery's :contains() Is Not CSS

:contains("text") is not CSS. It was proposed in early CSS3 drafts (Selectors Level 3) but removed from the specification before browsers implemented it. It survives in two places:

javascript
1// jQuery selector - this is jQuery's selector engine, not CSS
2$('p:contains("Warning")').addClass('warning');
3
4// Cypress testing framework - also not CSS
5cy.get('td:contains("Total")').should('have.class', 'amount');

jQuery and Cypress implement their own selector extensions. :contains() does not work in a stylesheet or in document.querySelector().

javascript
// This does NOT work - :contains is not a valid CSS selector
document.querySelectorAll('p:contains("Warning")');
// Throws: SyntaxError: 'p:contains("Warning")' is not a valid selector

Why :has() does not help

The :has() selector (now supported in Chrome, Safari, and Firefox) selects based on descendant elements, not text content.

css
1/* Select articles that contain an element with class error-badge */
2article:has(.error-badge) {
3  border: 2px solid red;
4}
5
6/* Select labels that have a required input as a sibling */
7label:has(+ input:required) {
8  font-weight: bold;
9}
10
11/* Select cards that contain an image */
12.card:has(img) {
13  padding: 0;
14}

:has() is structural: it can check for child elements but not their text.

Assigning classes at render time in React and Vue

Component frameworks handle this when rendering rather than in CSS:

React

jsx
1function StatusMessage({ text, status }) {
2  return (
3    <p className={`message message-${status}`}>
4      {text}
5    </p>
6  );
7}

Vue

html
1<template>
2  <p :class="['message', `message-${status}`]">
3    {{ text }}
4  </p>
5</template>

The class is assigned from component state during rendering, not by inspecting rendered text. Components decide which classes apply, and CSS decides what they look like.

Workarounds that break

The most frequent mistake is treating jQuery selectors or test framework locators as standard CSS. :contains() works in jQuery and Cypress but browsers do not support it in stylesheets or querySelector.

Attribute selectors like [title*="warning"] only stand in for text matching if the information is duplicated in an attribute, which is fragile and adds redundant data to the DOM.

Scanning and classifying text in JavaScript when you could add a class in the rendering component adds needless runtime cost. If you control rendering, add classes there; reserve text scanning for markup from external sources you cannot modify.

Text-based rules break under localization. A rule looking for "Warning" fails for users seeing "Advertencia" or "Avertissement". Classes and data attributes are language-independent.

Leaning on :has() as a replacement for text matching leads to brittle selectors. If the condition is truly text-based, use JavaScript.


Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Basis Lab
No course covers this one yet

Basis Lab writes one for you from a sentence about what you want to be able to do, then teaches it and checks you understood. Your first course is free.

Build my course
Data Structures & Algorithms practice on Codemia

Step through 300+ coding interview problems with animated visualisers that show the data structure changing as the code runs. The Blind 75 are free.

Practice algorithms