首页 > 解决方案 > 如何选择具有相同锚文本和href值的链接

问题描述

我想对锚点与 href 属性值相同的链接设置不同的样式:

<a href="https://google.com">https://google.com</a>

是否可以单独使用 CSS 来做到这一点,或者我需要 JavaScript 吗?

标签: javascripthtmlcss

解决方案


感谢您评论这在 CSS 中是不可能的。

我最终得到了这个 JavaScript 解决方案:

document.addEventListener("DOMContentLoaded", () => {
  for (item of document.querySelectorAll("a[href*='//']")) {
    if (item.getAttribute('href') == item.innerHTML) { 
      //item is an HTML link with anchor same as innerHTML.
      //in this case, I just add a class to it

      item.classList.add('no-after-content') 
    }
  }
})

推荐阅读