Disable all links by class

I want to disable/enable all links with a class of ‘modal’


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Title</title>
</head>
<body>

<h1>Hello</h1>

<p><a href="http://www.google.com" class="modal">Google Link</a></p>
<p><a href="http://www.example.com" class="xyz">This link should not be disabled/enabled</a></p>
<p><a href="http://www.example.com" class="modal">Example Link</a></p>

<input type="button" value="Disable Links" onclick="DisableLinks('modal');" />
<input type="button" value="Enable Links" onclick="EnableLinks('modal');" />

</body>
</html>

If you’re using jQuery to do this, here is how it’s done.


function DisableLinks(className) {
    $('a.' + className).click(function () {
        return false;
    });
}
function EnableLinks(className) {
    $('a.' + className).click(function () {
        return true;
    });
}

If you’re not using jQuery, I’ll repost with the solution shortly.

The script to enable/disable the links is:


function DisableLinks(className) {
    var links = document.getElementsByTagName('A'),
        linksLen = links.length,
        link,
        i;
    for (i = 0; i < linksLen; i += 1) {
        link = links[i];
        if (link.className === className) {
            disableLink(link);
        }
    }
}
function EnableLinks(className) {
    var links = document.getElementsByTagName('A'),
        linksLen = links.length,
        link,
        i;
    for (i = 0; i < linksLen; i += 1) {
        link = links[i];
        if (link.className === className) {
            enableLink(link);
        }
    }
}
function disableLink(el) {
    el.onclick = function () {
        return false;
    }
}
function enableLink(el) {
    el.onclick = function () {
        return true;
    }
}

There are all sorts of ways to improve this script, so that multiple class names on an emelent can be catered for, or to reduce the amount of duplication throughout the script, but this is the basic starting point from where further refinements can be made.

One example of such an improvement is to move the looping out to a separate function.


function DisableLinks(className) {
    var links = document.getElementsByTagName('A');
    forEachClass(className, links, disableLink);
}
function EnableLinks(className) {
    var links = document.getElementsByTagName('A');
    forEachClass(className, links, enableLink);
}
function disableLink(el) {
    el.onclick = function () {
        return false;
    }
}
function enableLink(el) {
    el.onclick = function () {
        return true;
    }
}
function forEachClass(className, els, fn) {
    var elsLen = els.length,
        el,
        i;
    for (i = 0; i < elsLen; i += 1) {
        el = els[i];
        if (el.className === className) {
            fn(el);
        }
    }
}