Home >Web Front-end >CSS Tutorial >Can I Style Anchors Based on their Content Using CSS?
Can CSS be used to apply a distinct style to anchors that contain a specific word?
Unfortunately, pure CSS does not offer a native solution to style elements based on their content. The proposed ':contains' selector is not part of the current CSS3 Selectors Working Draft.
To achieve this functionality, JavaScript can be used. For example, the following code snippet iterates through all links in the document and applies a red color to any anchor whose content matches the string "SpecificWord":
Array.from(document.links).forEach(link => { if (/\bSpecificWord\b/i.test(link.innerHTML)) { link.style.color = 'red'; } });
This example HTML demonstrates the effect of the script:
<a href="#">SpecificWord</a> <a href="#">OtherWords</a>
Upon execution, the first anchor will be styled with a red color, while the second will retain its default styling.
The above is the detailed content of Can I Style Anchors Based on their Content Using CSS?. For more information, please follow other related articles on the PHP Chinese website!