Use JavaScript to find a specific link

僤鯓⒐⒋嵵緔 提交于 2019-12-20 07:23:02

问题


Could anyone help me with a function for JavaScript which searches the source code and compares all of the links on the site with the specific link I am looking for.

For example: I am executing the JavaScript on www.youtube.com and I am looking for one specific YouTube link.

It could look like this (which of course doesn't work):

if(document.body.indexOf("http://www.youtube.com/SPECIFICURL")!== -1){
    console.log("Url found");
}else{
  console.log("Url not found");

}

How can I accomplish this?


回答1:


function find_link_by_href(address)
    links = document.getElementsByTagName("a");

    for(var i = 0; i < links.length; i++) { 
      if( links[i].href === address ) {
        console.log("Url found"); 
        return; 
     } 
 }

You can call it like this:

find_link_by_href("http://www.youtube.com/SPECIFICURL");



回答2:


Try querySelectorAll() with CSS3 selectors:

document.querySelectorAll('a[href*="http://www.youtube.com/SPECIFICURL"]')

Fiddle

This selector says find all links with an href attribute that contains a specific string. Lets break this down a little bit:

  • a - this is the element type, e.g. "link"
  • href - this is the element attribute
  • *= - this essentially means contains. There are different type of equality checks that can be used: starts with, contains word, ends with, etc. The jQuery selectors documentation is quite good.
  • "..." - everything in quotes after the equal sign is the substring the query is looking for.



回答3:


Use Array.prototype.some to see if at least one element in document.links has the href you're looking for.

var has_link = [].some.call(document.links, function(link) {
   return link.href === 'http://www.youtube.com/SPECIFICURL';
});

You can patch it in old browsers using the patch found at MDN Array#some




回答4:


You can use document.links to get the anchors, then just loop through grabbing the href, like this:

    var arr = [], l = document.links;
    for(var i=0; i<l.length; i++) {
      arr.push(l[i].href);
    }

//arr is now an array of all the href attributes from the anchors in the page

See here.

Then loop through the array to check for your specific link.



来源:https://stackoverflow.com/questions/22204218/use-javascript-to-find-a-specific-link

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!