如何选择具有相同锚文本和href值的链接?

时间:2018-05-01 12:06:29

标签: javascript html css

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

function findAndCompare($url){

    // Create a DOM parser object
    $dom = new DOMDocument();

    // load HTML from URL
    $dom->loadHTMLFile($url);

    // Iterate over all the <a> tags
    foreach($dom->getElementsByTagName('a') as $link) {
        // Show the <a href>
        echo $link->getAttribute('href');
        echo "<br />";
    }
}

是否可以单独使用CSS,或者我是否需要JavaScript?

2 个答案:

答案 0 :(得分:1)

感谢您对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') 
    }
  }
})

答案 1 :(得分:0)

使用javascript的简单解决方案。希望这有帮助。

&#13;
&#13;
<a href="https://google.com">https://google.com/</a><br />
<a href="https://google.com">https://yahoo.com/</a>

<script>
var myCol = document.getElementsByTagName("a");
for(i=0; i<  myCol.length; i++){

if((myCol[i].href).trim() == (myCol[i].innerHTML).trim()){
  myCol[i].style.color = "red";
}

}

</script>
&#13;
&#13;
&#13;