Reputation: 19
I have one jQuery function which executes for each anchor tag from the page which needs to be checked that acnhor tag should contains herf attribute with URL of any site. It should return false in case if anchor tag does not contains href tag or href tag having the values link blank, mailto, #, tel:1000 etc.
Means condition should check anchor tag should have href tag & hreg tag should contain URL only.
$('a').each(function() { //add a class to all external links
var $a = jQuery(this);
var domainURL = $a.get(0).href;
var hostToDetectAsExternal = domainURL.replace('http://','').replace('https://','').replace('www.','').split(/[/?#]/)[0];
if(domainURL != '' && domainURL.indexOf('javascript') == -1 && allwedHostsArray.indexOf(hostToDetectAsExternal) == -1) // -1 : Not found in a allowed hosts array & not found javacript in a URL
{
$a.addClass('external-link');
}
});
have written this code but not fulfilling all the conditions. Please anyone help me out.
Upvotes: 0
Views: 1041
Reputation: 370639
Use the selector string a[href^="http"]
to select a
s whose href
attributes start with http
(which, of course, will also include those which start with https
)
$('a[href^="http"]').each(function() {
If you wanted to include all URL-based href
s and not just external links or absolute paths, you could add a[href^="/"]
as well, to match a
s with relative URLs:
$('a[href^="http"], a[href^="/"]').each(function() {
Upvotes: 2