admin管理员组

文章数量:1287979

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>

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.

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

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

Is this possible with pure JavaScript and not jQuery?

Share Improve this question edited Jan 29, 2019 at 9:45 Luke Girvin 13.5k10 gold badges67 silver badges85 bronze badges asked Oct 23, 2017 at 11:39 AsimAsim 9762 gold badges10 silver badges30 bronze badges 1
  • @Ayush No, i want to hide all the a href elements that have url=example. and not url=example2.. the ID can be same ("someID") – Asim Commented Oct 23, 2017 at 11:47
Add a ment  | 

4 Answers 4

Reset to default 5

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.']").style.display = 'none';
<a href="www.example." id="someID" style="display:block">Check</a>
<a href="www.example2." 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./') {
    anchors[i].style.display = 'none';
  }
}
<a href="https://example./" id="someID">Check</a>
<a href="https://example2./" id="someID">Check</a>

You can use javascript to do the job. Use querySelector to get all the elements with same id. Then loop the ids and pare 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.") {
    elements[i].style.display='none';
  }
}
</script>

Working fiddle link

You can make condition

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

if (url.href = "www.example.")
{
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

本文标签: javascriptHide Anchor tag based on href URLStack Overflow