Javascript - get all anchor labels and compare them with an array

I try forever, but it just does not work, how can I check the array of URLs that I received ( document.getElementsByTagName('a').href;) to see if there is any of the sites in another array?

+3
source share
3 answers
var linkcheck = (function(){
  if(!Array.indexOf){
    Array.prototype.indexOf = function(obj){
  for(var i=0; i<this.length; i++){
    if(this[i]===obj){
      return i;
    }
  }
      return -1;
    }
  }
  var url_pages = [], anchor_nodes = []; // this is where you put the resulting urls
  var anchors = document.links; // your anchor collection
  var i = anchors.length;
  while (i--){
    var a = anchors[i];
    anchor_nodes.push(a); // push the node object in case that needs to change
    url_pages.push(a.href); // push the href attribute to the array of hrefs
  }
  return {
    urlsOnPage: url_pages, 
    anchorTags: anchor_nodes, 
    checkDuplicateUrls: function(url_list){
      var duplicates = []; // instantiate a blank array
      var j = url_list.length;
      while(j--){
        var x = url_list[j];
        if (url_pages.indexOf(x) > -1){ // check the index of each item in the array.
          duplicates.push(x); // add it to the list of duplicate urls
        }
      }
      return duplicates; // return the list of duplicates.
    },
    getAnchorsForUrl: function(url){
      return anchor_nodes[url_pages.indexOf(url)];
    }
  }
})()
// to use it:
var result = linkcheck.checkDuplicateUrls(your_array_of_urls);

JavaScript , , , . , , URL- , . , , . URL- ( ). indexOf IE8 document.getElementsByTagName document.links, .

+2

getElementByTagName ( ).

var a = document.getElementsByTagName('a');

for (var idx= 0; idx < a.length; ++idx){
    console.log(a[idx].href);
}

, jquery. .

jquery:

$("a").each(function(){
  console.log(this.href);
});
+11

Jquery u - -

$('a').each(function(){
if( urls.indexOf(this.href) !- -1 )
    alert('match found - ' + this.href );
})

urls is your existing array with which you need to compare.

-1
source

Source: https://habr.com/ru/post/1767640/


All Articles