Last active
November 8, 2019 07:55
-
-
Save jverweijL/24f12cd18bead0331411901625652392 to your computer and use it in GitHub Desktop.
detect brokenlinks
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // inspired by https://stackoverflow.com/questions/1591401/javascript-jquery-check-broken-links | |
| function urlExists(element, callback) { | |
| var xhr = new XMLHttpRequest(); | |
| xhr.onreadystatechange = function() { | |
| if (xhr.readyState === 4) { | |
| callback(xhr.status < 400); | |
| } | |
| }; | |
| xhr.open('HEAD', element.attr("href")); | |
| xhr.send(); | |
| } | |
| $(function() { | |
| $( "a" ).each(function( index ) { | |
| var element = $(this); | |
| urlExists(element, function(exists) { | |
| console.log('"%s" exists?', element.attr("href"), exists); | |
| if (!exists) { | |
| element.addClass("brokenlink"); | |
| } | |
| }); | |
| }); | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment