Home > Net >  How to remove the link from all the a tags on a page with pure js?
How to remove the link from all the a tags on a page with pure js?

Time:04-16

I'm trying to inject js to loop through all the a tags in a page and remove the href so that they don't go anywhere when clicked.

For this issue, I can't use jquery. So I need to use it using vanilla js (pure js). Here's what I have so far:

document.querySelectorAll("a").forEach(ele => {
    var anchors = document.getElementsByTagName("a");
    for(var i =0; i < anchors.length; i  )
    {       var myLink = anchors[i].getAttribute("href");
            anchors[i].setAttribute("href","");
    }
});

I ran the code, but none of the href tags were changed. They are all still links. How to get all the a tags to not work as links?

I'm also open to other solutions, like turning the a tags into divs, or something else.

CodePudding user response:

Setting the attribute to an empty string will result in the anchors pointing to the current page:

<a href="">link</a>

Remove the attribute entirely instead (and remove the unnecessary and unused outer loop).

var anchors = document.getElementsByTagName("a");
for (var i = 0; i < anchors.length; i  ) {
  anchors[i].removeAttribute("href");
}
<a href="https://example.com">link</a>
<a href="https://example.com">link</a>

or

for (const a of document.querySelectorAll('a')) {
  a.removeAttribute("href");
}
<a href="https://example.com">link</a>
<a href="https://example.com">link</a>

CodePudding user response:

You can remove the href link attribute by using jquery

    $( "a" ).each( function( index, element ){
     element.removeAttribute("href");
   });
  • Related