Find links in an HTML document using Javascript / jQuery

This is a problem for any jinjavas / jQuery ninjas:

What is the best way (using the above languages) to find all links in an HTML document and return them all?

In other words, a function like this is findLinks (document.html.innerHTML) , which will return all the links found in this HTML.

Thanks,

DLiKS

+4
source share
4 answers

Well, you could play around with a small library (and it might be a good idea to do this if you end up doing interesting things to manipulate the results), but just to get the links, I think stick with DOM 0:

document.links 
+7
source

To get all hrefs from existing anchor elements, you can do the following, which will return them as an array:

 var links = $("a").map(function() { return this.href; }).get(); 

If you just want to capture each anchor element and then do something with them, you just need to select them:

 $("a").hide(); // or whatever 
+2
source

I have a bookmarklet that finds all the hyperlinks and writes them to an HTML page:

JavaScript: ctDL = document.links; ctWI = open ('', '', 'width = 400, height = 300, scrollbars, mutable, MenuBar'); ctDO = ctWI.document; ctDO.writeln (''), for (CTI = 0;% 20ctI ')} voids (ctDO.close ())

0
source

This is either I do not understand the question, or it is not so difficult:

 function findLinks(innerHTML){ var fragment = document.createElement('div'); fragment.innerHTML = innerHTML; var links = []; fragment.find('a').each(function(index, element){ links.push($(element).attr('href')); }); return links; } 
0
source

All Articles