How to Select an Element Based on Its Inner Text Using CSS and JavaScript

How to Select an Element Based on Its Inner Text Using CSS and JavaScript

Table of Contents

Select an element based on its inner text using CSS for styling or JavaScript for manipulation by leveraging selectors like :contains (via JS libraries) or custom JS functions.

When working with web development, there are times when you might need to style or manipulate an element based on its text content. For instance, imagine you have multiple headings on a webpage, and you want to apply specific styles only to the <h2> element that contains the text “Frequently Asked Questions.”

While CSS is a powerful tool for styling, it has limitations when it comes to selecting elements based on their inner text. This is because CSS selectors primarily work with element types, attributes, classes, and IDs—not content. However, JavaScript provides a solution to bridge this gap. In this article, we’ll explore why CSS alone cannot accomplish this task, how JavaScript can help, and practical examples to achieve this functionality.


Problem Overview

Let’s say you have the following HTML structure:

<h2 class="wp-block-heading">Frequently Asked Questions</h2>
<h2 class="wp-block-heading">General Information</h2>
<h2 class="wp-block-heading">Contact Details</h2>

You want to specifically target the <h2> element with the exact text “Frequently Asked Questions” to apply a unique style, such as changing its color to red.


Why CSS Alone Is Insufficient

CSS, by design, does not provide a built-in method to select elements based on their text content. CSS selectors are limited to:

  • Element types (h2, p, div, etc.).
  • Classes and IDs (.class-name or #id-name).
  • Pseudo-classes (:hover, :nth-child, :first-child, etc.).
  • Attribute selectors ([data-attribute="value"]).

While newer experimental pseudo-classes like :has() and :contains() have been proposed, they are not widely supported by modern browsers. For example, :contains() (available in jQuery) is not part of standard CSS. As a result, you cannot write a rule like this:

h2:contains("Frequently Asked Questions") {
    color: red;
}

Since this won’t work in standard CSS, we must turn to JavaScript for a reliable solution.


The JavaScript Solution

JavaScript provides an easy and flexible way to select elements based on their inner text. By using methods like querySelectorAll() and iterating through elements, you can target the specific text content you want.

Example Code

Here’s a basic JavaScript example to achieve this:

document.querySelectorAll('h2').forEach((element) => {
    if (element.textContent.trim() === 'Frequently Asked Questions') {
        element.classList.add('highlight');
    }
});

How It Works:

  1. document.querySelectorAll('h2'): This selects all <h2> elements on the page.
  2. .forEach: Iterates through the list of <h2> elements.
  3. textContent.trim(): Retrieves the inner text of the element and trims any extra whitespace.
  4. === 'Frequently Asked Questions': Compares the element’s text content to the target string.
  5. .classList.add('highlight'): Adds a custom CSS class (highlight) to the matched element.

Applying Styles Using CSS

Once you’ve added the highlight class using JavaScript, you can define its styles in your CSS file:

.highlight {
    color: red;
    font-weight: bold;
    text-decoration: underline;
}

Now, only the <h2> element with the text “Frequently Asked Questions” will be styled.


Full Example

HTML:

<h2 class="wp-block-heading">Frequently Asked Questions</h2>
<h2 class="wp-block-heading">General Information</h2>
<h2 class="wp-block-heading">Contact Details</h2>

JavaScript:

document.querySelectorAll('h2').forEach((element) => {
    if (element.textContent.trim() === 'Frequently Asked Questions') {
        element.classList.add('highlight');
    }
});

CSS:

.highlight {
    color: red;
    font-weight: bold;
    text-decoration: underline;
}

Alternative: Using jQuery

If your project includes jQuery, you can simplify the process further with its built-in :contains() selector:

$('h2:contains("Frequently Asked Questions")').addClass('highlight');

This snippet will find all <h2> elements containing the text “Frequently Asked Questions” and add the highlight class to them.


Advanced: Handling Dynamic Content

In modern web applications, content is often loaded dynamically (e.g., via AJAX or an API). If the target element is added to the DOM after the initial page load, you’ll need to ensure your JavaScript runs after the content is available.

Using a MutationObserver

For dynamically added elements, you can use the MutationObserver API to monitor changes in the DOM:

const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
        mutation.addedNodes.forEach((node) => {
            if (node.nodeType === 1 && node.tagName === 'H2' && node.textContent.trim() === 'Frequently Asked Questions') {
                node.classList.add('highlight');
            }
        });
    });
});

observer.observe(document.body, { childList: true, subtree: true });

This ensures the script works even if the <h2> element is added dynamically.


When to Use This Approach

Targeting elements based on text content can be useful in several scenarios:

  1. Localized Content: Apply styles to specific headings or labels in multilingual websites.
  2. CMS Templates: Dynamically style headings in platforms like WordPress or Drupal without altering the underlying HTML.
  3. Dynamic Web Applications: Highlight or modify specific content loaded via APIs.

Conclusion

While CSS is an essential tool for styling, it lacks the ability to select elements based on their inner text. JavaScript offers a practical and reliable solution to this limitation. By combining JavaScript’s text selection capabilities with CSS styling, you can achieve precise control over your webpage’s appearance.

This approach is particularly useful for dynamic or localized content where IDs or class names cannot be relied upon. Whether you’re working on a personal project or a large-scale application, mastering this technique will enhance your web development toolkit. working with CMS platforms like WordPress.

Click to rate this post!
[Total: 0 Average: 0]
Send us a Message
We would love to hear from you!