user7211
user7211

Reputation: 3

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

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.

Upvotes: 0

Views: 286

Answers (2)

Siraj Ali
Siraj Ali

Reputation: 604

Try this code

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371233

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>

Upvotes: 3

Related Questions