Can I Style Anchors Based on their Content Using CSS?

Linda Hamilton
Release: 2024-11-21 08:26:13
Original
514 people have browsed it

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';
  }
});
Copy after login

This example HTML demonstrates the effect of the script:

<a href="#">SpecificWord</a>
<a href="#">OtherWords</a>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template