Disable and enable all hyperlinks inside a div using javascript

Simple javascript that disable and enable all the hyperlinks inside a div tag. Interesting right. Here is the script that disable all links. You need to pass the function accordingly. Say for example if you have a div tag with id=”main” then you can disable all the hyperlinks inside the div tag by passing disableLinksByElement(main).
The html will look like this.

<div id="main">
<!-- Your Hyperlinks -->
</div>
<a href="javascript:disableLinksByElement(main)">Disable All Links</a>

Make sure that your “Disable All Links” Hyperlink is outside the div tag with id=”main”

function disableLinksByElement(el) {
  if (document.getElementById && document.getElementsByTagName) {
    if (typeof(el) == 'string') {
      el = document.getElementById(el);
    }
    var anchors = el.getElementsByTagName('a');
    for (var i=0, end=anchors.length; i<end; i++) {
      anchors[i].onclick = function() {
        return false;
      };
    }
  }
}

For this everything is the same and if you want to enable all the links inside div tag with id=”main” then pass this enbleLinksByElement(main)
The html will look like this

<a href="javascript:enableLinksByElement(main)">Enable All Links</a>
function enableLinksByElement(el) {
  if (document.getElementById && document.getElementsByTagName) {
    if (typeof(el) == 'string') {
      el = document.getElementById(el);
    }
    var anchors = el.getElementsByTagName('a');
    for (var i=0, end=anchors.length; i<end; i++) {
      anchors[i].onclick = function() {
        return true;
      };
    }
  }
}

We will be coming soon with a detailed tutorial that disable and enables hyperlinks in the next post. This is just a beginning, Stay focused 🙂

Click to rate this tutorial!
[Total: 8 Average: 4.1]

Leave a Reply

Your email address will not be published. Required fields are marked *