how check if link go for certain site using javascript
ho开发者_StackOverfloww check if link go for certain site using javascript
function checkLinks() {
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i];
if (anchor.href == "http://google.com"){/*compare not working*/
alert("exist");
}
}
}
Try using anchor.getAttribute('href')
.
You could use regexp to try and match the links. With this method, it checks if it is directing to that domain (what exact url doesn't matter, as long as it has "google.com" somewhere in the URL):
function checkLinks() {
var anchors = document.links;
for (var i=0; i<anchors.length; i++){
var anchor = anchors[i].href;
var re = new RegExp("google\.com","ig");
if (re.test(anchor)){
alert("exist");
}
}
}
example: http://jsfiddle.net/niklasvh/ELg6d/
Your compare isn't working because that's not what .href is returning. I'm guessing if you looked at the actual value of href, it would have another '/' on the end.
精彩评论