How to disable all <a> links using javascript in Firefox and Chrome

18,053

Solution 1

If you don't want to change the href of the links, one could do this too:

window.onload = function() {
    var anchors = document.getElementsByTagName("a");
    for (var i = 0; i < anchors.length; i++) {
        anchors[i].onclick = function() {return false;};
    }
};

Working demo here: http://jsfiddle.net/jfriend00/9YkJQ/.

Solution 2

This is a very old thread but just in case someone else comes to this page, the disabled attribute can be set by using:

element.setAttribute('disabled', 'disabled');

This is recognized in all browsers and will disable the link. However, firing events on a disabled link is handled differently in different browsers & versions. FF & Chrome will still fire the onclick event where IE8+, not in compatibility mode, will not fire events. This is not necessary if there is no onclick event handler wired to the anchor, a normal href will not fire once the disabled attribute has been set. To stop the firing of the click event, the above code would work. The parens are not required and personally, I don't use them in this case as I assume parens are for grouping or for a function. Seems unnecessary in the solution provided before.

Share:
18,053
ran
Author by

ran

Updated on June 26, 2022

Comments

  • ran
    ran about 2 years

    I want to disable all href links in my page. i am using the below code and it is working fine only in IE.

    var elems = document.getElementsByTagName("*");
        var len = elems.length;
        for (i=0; i<len; i++) {
               if(elems[i].tagName.toLowerCase() == 'a'){
                   elems[i].disabled = true;           
               }
           }
    

    but i want work it on all browsers. can somebody please help me how to overcome this issue.

    Thanks in advance.