Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get value of href attribute of <a> tag without jQuery

Is any way, how to without jQuery get from string value of href attribute in "a" tag? I have got string with (for example) this content - <a href="www.something">.

How can I get value of href attribute to variable?

like image 976
user2316602 Avatar asked Jul 05 '13 12:07

user2316602


People also ask

How to get the value of the href attribute in jQuery?

The jQuery attr () method is used to get attribute values. The following example demonstrates how to get the value of the href attribute in a link: The next chapter explains how to set (change) content and attribute values.

How do I get the attribute value of a link?

Get Attributes - attr() The jQuery attr() method is used to get attribute values. The following example demonstrates how to get the value of the href attribute in a link: $("button").click(function(){. alert($("#w3s").attr("href"));

How do I get the value of an attribute in HTML?

Getting it via getAttribute returns the actual attribute's value rather than the fully-qualified version, and the href reflected property gets the fully-qualified version (e.g., relative links get expanded). Getting a reference to the element is a broad topic.

How do I get the value of an anchor tag in JavaScript?

Using JavaScript In vanilla JavaScript, you can use the querySelector(), which will return the first anchor tag within the document. Then we can directly access the href property to get the exact value of the href attribute.


1 Answers

I have got string with (for example) this content - <a href="www.something">

If it is actually in a string as follows:

var s = '<a href="www.something">';

Then you can use a regex with the .match() method:

var href = s.match(/href="([^"]*)/)[1];
// href is now www.something

If it is an element on your page then have a look at T.J. Crowder's answer (no need for me to duplicate that information here).

like image 125
nnnnnn Avatar answered Oct 18 '22 21:10

nnnnnn