Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract href from html with jQuery

Tags:

jquery

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'>File</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.

like image 452
Craig552uk Avatar asked Jun 18 '10 22:06

Craig552uk


People also ask

How to give href value in jQuery?

Answer: Use the jQuery . attr() Method You can use the jQuery . attr() method to dynamically set or change the value of href attribute of a link or anchor tag. This method can also be used to get the value of any attribute.

What method can be used to retrieve the href attribute of an element?

We can get an attribute value from a href link in Selenium. To begin with, we have to first identify the element having an anchor tag with the help of any of the locators like css, id, class, and so on. Next, we shall use the getAttribute method and pass href as a parameter to the method.


2 Answers

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.

like image 193
gnarf Avatar answered Sep 24 '22 10:09

gnarf


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'>File</a>";

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

Otherwise the answers that gnarf and Dzida gave are excellent.

like image 26
user113716 Avatar answered Sep 26 '22 10:09

user113716