iltdev
iltdev

Reputation: 1835

JQuery - Getting an attribute value from a variable

I'm trying to get the href attribute from a div with the class name 'download'. I know I could use the following to access it from the DOM:

I know you can use $(".download").attr("href");

However, the html doesn't exist in the DOM yet, its only in a variable.

Is there a way to get from href from a variable?

Upvotes: 2

Views: 7646

Answers (2)

Samich
Samich

Reputation: 30095

Yes, you can:

$('<div class="download"><a href="example.com/image.png">Download</a></div>').find('a').attr('href')

http://jsfiddle.net/Ufz37/1

Upvotes: 1

KARASZI Istv&#225;n
KARASZI Istv&#225;n

Reputation: 31467

Assuming you have the following code (or something similar):

var $a = $(document.createElement('a'))
  .addClass('download')
  .attr('href', 'http://stackoverflow.com/');

Then you can get the href attribute from the $a variable with:

var href = $a.attr('href');

Upvotes: 0

Related Questions