Get value of href attribute of <a> tag without jQuery
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).
If you really have that as a string, then refer to nnnnnn's answer.
Or alternately, if you're in the browser environment:
var str = '<a href="www.something">';
var div = document.createElement('div');
div.innerHTML = str + "</a>"; // Make it a complete tag
var link = div.firstChild.getAttribute("href");
If you have an actual element on a page created via that markup, then:
If you have a reference to the element, you can get the href
from it like this:
var link = theElement.href;
// or
var link = theElement.getAttribute("href");
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. If it has an id
, you can use getElementById
. Or if you're responding to an event and the event is happening on an element near the one you want, you can use various DOM properties and methods to navigate to it. With a lot of modern browsers, you can use CSS selectors and either querySelector
(find one element) or querySelectorAll
(a list).
For instance, this gives you the href
of the first link on the page that has the class "foo"
:
console.log(document.querySelector("a.foo").href);
Full example: Live Copy | Live Source
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>Getting the Link</title>
</head>
<body>
<a id="theLink" href="/relative/link">Link</a>
<script>
(function() {
var theLink = document.getElementById("theLink");
display("<code>href</code> property: " + theLink.href);
display("<code>getAttribute('href')</code>: " +
theLink.getAttribute("href"));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
})();
</script>
</body>
</html>