Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use JavaScript to find a specific link

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?

like image 848
user3361146 Avatar asked Dec 02 '22 16:12

user3361146


1 Answers

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.
like image 166
DontVoteMeDown Avatar answered Dec 09 '22 22:12

DontVoteMeDown