CSS selector containing specific text

CSS Selector Contains Specific Text

CSS Selector Contains Specific Text

In web development, we often need to select various elements on the page based on text content. CSS selectors are a powerful tool that can help us achieve this. In this article, we’ll focus on how to use CSS selectors to select elements containing specific text.

Basic Concepts

In CSS, a selector is a pattern used to select HTML elements. By setting different selectors, we can select and style different elements on a page. Common CSS selectors include element selectors, class selectors, ID selectors, descendant selectors, and pseudo-classes.


To select elements containing specific text, we can use attribute selectors. Attribute selectors allow us to select elements based on their attribute values. By leveraging the “Contains Specific Text” feature in attribute selectors, we can easily select elements that contain specific text.

Using Attribute Selectors to Contain Specific Text

In CSS, attribute selectors allow you to select elements based on their attribute values. Attribute selectors that contain specific text use the *= symbol to match. For example, to select all elements containing the text “example,” we can use the following CSS selector:

[data-text*="example"] {
/* Add style */
}

The above selector will select all elements whose data-text attribute value contains the text “example.” This allows us to easily apply style adjustments to these elements.

Example Code

Let’s take a look at a practical example. Suppose we have the following HTML code:

<div data-text="example1">This is a div containing the text "example1"</div>
<div data-text="example2">This is a div containing the text "example2"</div>
<div data-text="foo">This is a div that does not contain any specific text</div>

Now we want to highlight elements containing the text “example” by selecting and styling them using a CSS selector. We can write the following CSS code:

[data-text*="example"] {
color: red;
font-weight: bold;
}

This way, all elements containing the text “example” will turn red and bold.

Result

Based on the example code above, when we apply the HTML and CSS code to the page, we will see the following result:

  • This is a div containing the text “example1”
  • This is a div containing the text “example2”

The two elements containing the text “example” will turn red and bold, while elements that do not contain the specified text will remain unaffected.

Summary

By using the “Contains Specific Text” feature in attribute selectors, we can easily select elements on the page that contain specific text and adjust their styles. This is a very useful technique in web development, allowing us to achieve more flexible and precise styling.

Leave a Reply

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