CSS Selectors: Using the :contains() Pseudo-class for Text-Based Element Selection
Learn how to use the :contains() pseudo-class in CSS selectors to target HTML elements based on their text content. This guide explains the syntax, usage, browser compatibility considerations, and provides examples illustrating its application in selecting elements based on their text.
CSS Selectors: Using the :contains() Pseudo-class
Introduction to :contains()
The :contains()
pseudo-class in CSS allows you to select HTML elements based on their text content. It's a useful way to locate elements when you know part or all of the text displayed within that element.
:contains() Syntax
The syntax is:
element:contains("text") { /* CSS styles */ }
This selects any element of the specified element
type that contains the exact text string provided within the contains()
pseudo-class. Note that this selector is not part of standard CSS and might not be supported in all browsers or testing frameworks; its availability often depends on the particular tools or libraries you're using (like certain versions of Selenium IDE).
Example: Locating a Button
Suppose you have this HTML (replace with your actual HTML):
<button>Click Me</button>
<button type="submit">Submit Form</button>
To select the button with the text "Submit Form":
button:contains("Submit Form") {
background-color: yellow;
}
Only the button containing "Submit Form" will have a yellow background.
Using :contains() in Selenium IDE (Illustrative)
In Selenium IDE, you'd use this selector in the "Target" field of your commands (e.g., "click", "type"). This assumes the selector is supported by your version of Selenium IDE. Remember to verify that the selector correctly identifies your element.