Styling Anchors Based on Content Using CSS
Can you apply distinct styling to anchors containing a specific word using pure CSS? Though the proposal of the :contains selector was considered in the past, it's currently not part of the official CSS3 Selectors specification.
Solution:
Since pure CSS lacks the ability to target anchors based on their content, JavaScript becomes the alternative solution.
Array.from(document.links).forEach(link => { if (/\bSpecificWord\b/i.test(link.innerHTML)) { link.style.color = 'red'; } });
This script will iterate through all the links on a page and check if they contain the "SpecificWord" string anywhere within their HTML content. If a match is found, the link's color will be set to red, as specified in the style property.
Usage:
To use this solution, you can embed the script into an HTML page. Here's an example:
<a href="#">SpecificWord</a> <a href="#">OtherWords</a> <script> Array.from(document.links).forEach(link => { if (/\bSpecificWord\b/i.test(link.innerHTML)) { link.style.color = 'red'; } }); </script>
This script will turn the first anchor element red, as it contains the "SpecificWord" string.
The above is the detailed content of Can You Style Anchors Based on Their Content Using Pure CSS?. For more information, please follow other related articles on the PHP Chinese website!