Check if the anchor tag has valid target

Posted By : Arun Kumar | 28-Jun-2016

What we are going to do in this tutorial,is to add a class "valid" if the anchor tag has a valid link in the href attribute or if it is not valid then we will add
"in-valid" class.


Let's create out html markup first.

 

<html>

<head>

<title>Check anchor tag validity</title>

</head>

<body>

<h2>Check anchor target</h2>

<a href="http://www.example.com" >Example.com</a>

</body>

</html>

 


We are going to use jquery's ajax method to get the header of the target page. So do not forget to include jquery in the html page.

 Let's start with the document ready event.

<script>

$(document).ready(function(){

  $('a').each(function(){

    var anchor = $(this);

    var url = anchor.attr('href');

    $.ajax({

    method:'HEAD',

    url:url

    })

    .success(function(){

      anchor.addClass('valid');

    })

    .error(function(){

        anchor.addClass('in-valid');

    });

  });

});

</script>

 

We are using each() method of jquery to loop through all the anchors in the page. And then read the href attribute and store it in the 'url' variable , declared locally.

Then we will use jquery's ajax method to hit the url and recieve the result.If its a success then the instructions inside the success method will be executed or it its an error the the instructions inside the error method will be executed.

The Ajax method of jquery supports other method's as well such as 'GET'. The reason being we are using 'HEAD' method is because this ajax call will return only the headers of the page from the server but the method 'GET' would have downloaded the full page from the header.

 

THANKS

About Author

Author Image
Arun Kumar

Arun is a creative UI Developer

Request for Proposal

Name is required

Comment is required

Sending message..