erniberni
erniberni

Reputation: 391

Javascript, get all links from a page with exclusion?

I want to get all links <a></a> from a page and got this code that is working without any problem:

var array = [];
var links = document.getElementsByTagName("a");
for(var i=0, max=links.length; i<max; i++) {
    array.push(links[i].href);
};
console.table(array);

Only thing left I would like to add here is some code to exclude links that have for example "google" or something in it, but I dont know how to do that (newbie in Javascript).

Hope someone can help me here, thanks in advance!

Upvotes: 0

Views: 53

Answers (2)

phuzi
phuzi

Reputation: 13060

You could always use Array.prototype.filter but getElementsByTagName returns a HTMLCollection and not an array. Fortunately there's a simple way to pretend it's an array and use the filter function - [].filter.call(htmlCollection, filterFunc).

var links = document.getElementsByTagName("a");
var array = [].filter.call(links, link => !link.href.toLowerCase().includes('google'))
  .map(link => link.href);
  
console.log(array);
<a href="https://google.com">Google</a>
<a href="https://oracle.com">Oracle</a>
<a href="https://microsoft.com">Microsoft</a>

Upvotes: 1

XMehdi01
XMehdi01

Reputation: 1

some code to exclude links that have for example "google" or something

You need to add if condition and check with includes method

var array = [];
var links = document.getElementsByTagName("a");
for(var i=0, max=links.length; i<max; i++) {
    let link = links[i].href;
    if(link.includes('google')==false) // if(!link.includes('google'))
        array.push(link);
};
console.table(array);

Upvotes: 1

Related Questions