S Nyxism
S Nyxism

Reputation: 13

Check if a link on the page contains a string

(I'm a complete newbie so please forgive me if this isn't clear!)

Is there a way to check if a URL (on the page, not of the page) contains a certain string, and then open said link? e.g. on a news website, check if a link (article) on the page contains "entertainment" and then open any links that contain that, in order to open all articles related to entertainment.

I've only been able to do it for if the URL of the page I'm on contains xyz, using window.location.href.indexOf, and not for URLs that are on the page.

Upvotes: 1

Views: 4196

Answers (2)

Sumer
Sumer

Reputation: 2867

ES6 Style

for (let link of document.getElementsByTagName("a")) {
  if (link.href.search("stack") > -1)  link.click();
}

Upvotes: 0

Reinstate Monica Cellio
Reinstate Monica Cellio

Reputation: 26143

Here's an example of doing what you need. I've added 3 links in HTML and added some Javascript to find the one with the text stack in it and click it.

var links = document.getElementsByTagName("a");

for (var i = 0, l = links.length; i < l; i++) {
  var link = links[i];
  if (link.href.indexOf("stack") !== -1) {
    link.click();
  }
}
<a href="https://www.google.com">google</a><br/>
<a href="https://www.stackoverflow.com">stack overflow</a><br/>
<a href="https://bbc.co.uk">bbc</a>

Upvotes: 2

Related Questions