tags:

views:

64

answers:

3

I'm trying to get the value of href from an anchor. The code looks like this

var html = "<a href='http://path/to/file.pdf&#39;&gt;File&lt;/a&gt;";
alert(jQuery("a",html).attr("href"));

The only output I get is 'undefined'. I'm want to get "http://path/to/file.pdf".

Any help is greatly appreciated.

+6  A: 

Try:

jQuery(html).attr('href');

Or if the <a> tag is deeper in the html than your example:

jQuery(html).find('a').attr('href');

The jQuery() function will convert HTML strings into DOM objects, and return a jQuery object containing them for you.

gnarf
Nice and concise. Also good job for explaining why the `$(html)` business works.
Jamie Wong
+1. Just a note to the OP, I would avoid using "html" as a variable name, since jquery has a function called .html() which is used quite often.
womp
As a note to others looking for this, you can also do `jQuery(html).get(0).href` and use vanilla javascript.
Jim Schubert
Great stuff! Works a treat! Thank you all. :)
Craig552uk
@Craig - Sounds like you've accepted this answer. Don't forget to click the checkmark next it to confirm.
patrick dw
@patrick Apologies, and thanks for letting me know.
Craig552uk
A: 

Your code should look like to make it works as you want:

var html = "<a href='http://path/to/file.pdf'&gt;File&lt;/a&gt;";
alert($(html).attr("href"))
Lukasz Dziedzia
+1  A: 

To explain why your method doesn't work - when you do jQuery("a",html), you are searching for a elements inside the context of the element stored in html.

The only thing currently inside is the File text. If your string was wrapped in a div for example, it would work. <div><a href='...'>File</a></div>


I assume you have some other reason for creating a jQuery object. If not, and you don't want the extra overhead, you could use a regular expression.

Example: http://jsfiddle.net/e3Gyc/

var html = "<a href='http://path/to/file.pdf'&gt;File&lt;/a&gt;";

var result = html.match(/href='([^']+)'/)[1];

Otherwise the answers that gnarf and Dzida gave are excellent.

patrick dw
Ooo, on one hand, The explaination for `jQuery("a", html)` not working is great... On the other you are *gasp* advocating parsing HTML with RegExp... Risky Move - +1 :)
gnarf
@gnarf - Thanks for the + . :o) No, not advocating. I'm far too apathetic to be much of an advocate. ;o) Just making a point that you wouldn't necessarily need to create a jQuery object if fetching the `href` is the only purpose. Not likely the case, though. Admittedly, the usefulness of this solution is narrow and fraught with peril. +1 backatcha.
patrick dw