ホームページ > 記事 > ウェブフロントエンド > 純粋な CSS を使用してコンテンツに基づいてアンカーをスタイルできますか?
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.
以上が純粋な CSS を使用してコンテンツに基づいてアンカーをスタイルできますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。