4

This is a challenge for any Javascript/jQuery ninjas out there:

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

In other words, a function that like this - findLinks(document.html.innerHTML) that would return all links found in that HTML.

Thanks,

DLiKS

4
  • Only <a> tag's href or plain text that is formated like URL also? Commented Aug 5, 2010 at 11:46
  • document.html.innerHTML? So obliterate a traversable DOM in favor of its html string representation that you then have to parse? Commented Aug 5, 2010 at 11:47
  • @Cres: God forbid the OP might want to pass other HTML strings to the function... :-) Commented Aug 5, 2010 at 12:20
  • 1
    Any references to other URLs are links - so the links to external CSS and JS files need to be found. Commented Aug 5, 2010 at 12:22

4 Answers 4

7

Well, you could fiddle around with a chunky library (and it might be a good idea to do that if you end up wanting to do interesting things to manipulate the results), but just to get the links I think I'd stick to DOM 0:

document.links
Sign up to request clarification or add additional context in comments.

2 Comments

@Crescent: You're very welcome, it's always nice to see a fan :-)
WWAET? (What Would Andy E Think?)
2

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 grab each anchor element and do something with them thereafter, you would just need to select them:

$("a").hide(); // or whatever

1 Comment

@Cipi - if that's the requirement, then this probably needs a regex or such.
0

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,resizable,menubar');ctDO=ctWI.document;ctDO.writeln('');for(ctI=0;%20ctI')}void(ctDO.close())

Comments

0

It's either I don't understand the question, or it's not really that much of a challenge:

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.