简体   繁体   中英

Hide Anchor tag based on href URL

I was wondering if there is a possibility to HIDE anchor tags that refer to a particular URL. I know there is possible to hide based on id like this with JavaScript:

 document.getElementById('someID').style.display = 'none'; 
 <a href="#" id="someID" style="display: none">Check</a> 

But let's say I want to hide all anchor tags based on URL example: www.example.com

<a href="www.example.com" id="someID" style="display: none">Check</a>
<a href="www.example2.com" id="someID" style="display: none">Check</a>

I want to hide the first anchor tag, not the second that refers to example2.com

Is this possible with pure JavaScript and not jQuery?

You can use document.querySelector to select bu attribute value like this.I have used no jquery the only javascript is used.

 document.querySelector("[href='www.example.com']").style.display = 'none'; 
 <a href="www.example.com" id="someID" style="display:block">Check</a> <a href="www.example2.com" id="someID" style="display:block">Check</a> 

Simply loop through all anchor elements and then check their href :

 var anchors = document.getElementsByTagName('a'); for (var i = 0; i < anchors.length; i++) { if (anchors[i].href == 'https://example.com/') { anchors[i].style.display = 'none'; } } 
 <a href="https://example.com/" id="someID">Check</a> <a href="https://example2.com/" id="someID">Check</a> 

You can make condition

var url = document.getElementsByTagName('a');

if (url.href = "www.example.com")
{
url.style.display = none;
}

It is not exact code. i provided you example .kindly try it and let me know. It is for single . if you have many tags then loop all those

You can use javascript to do the job. Use querySelector to get all the elements with same id . Then loop the ids and compare the href link value.

<script>
var elements = document.querySelectorAll("[id='someID']");
for(var i = 0; i < elements.length; i++) {
  if (elements[i].getAttribute("href") === "www.example.com") {
    elements[i].style.display='none';
  }
}
</script>

Working fiddle link

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM