2

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?

2 Answers 2

1

Yes, you can:

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

http://jsfiddle.net/Ufz37/1

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

1 Comment

Thanks for this, Samich. The href in my code is on an achor. When I try the following I just get 'undefined'. alert($('<div class="download"><a href="example.com/image.png">Download</a></…);
0

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');

1 Comment

Thanks for your answer, KARASZI István. I'm not sure it will work for me a I don't have the href/url string on its own. The string I'm working with is html containing divs, classes, anchors etc. I need to extract the href from the entire string.

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.