Andrea Hasani Andrea Hasani - 1 month ago 6
HTML Question

Disable href tag when value = declared

I want to disable a href tag when the link of it is # , the reason i want to do this is because i have lots of post on my webpage that have links poiting to other sites that are my partners.
When i make a post i have a template that make it easier on me to put information on it and have the href link ready if anyone site that has to do with the post want a partnership and i link it to them .
Some of my old post have href tags with # value on it and when i click on them they open up my page on another tab so thats why i would like to disable it if possible with javascript (anyone other script language that can do the job is fine too)

Thanks

Answer

Simplest way would be:

var emptyAnchors = document.querySelectorAll('a[href="#"]');

for (var i = 0; i < emptyAnchors.length; i++) {
    emptyAnchors[i].addEventListener('click', preventDefaultEvent);
}

function preventDefaultEvent(e) {
    e.preventDefault();
}

This will prevent the default behavior on a link click (open the href target).

Comments