Home > Web Front-end > CSS Tutorial > Can You Style Anchors Based on Their Content Using Pure CSS?

Can You Style Anchors Based on Their Content Using Pure CSS?

Susan Sarandon
Release: 2024-11-15 07:46:02
Original
1023 people have browsed it

Can You Style Anchors Based on Their Content Using Pure 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';
  }
});
Copy after login

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>
Copy after login

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!

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