Home >Web Front-end >CSS Tutorial >Can I Style Anchors Based on their Content Using CSS?

Can I Style Anchors Based on their Content Using CSS?

Linda Hamilton
Linda HamiltonOriginal
2024-11-21 08:26:13560browse

Can I Style Anchors Based on their Content Using CSS?

CSS Rule Based on Content

Can CSS be used to apply a distinct style to anchors that contain a specific word?

Answer

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.

JavaScript Workaround

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn