Reputation: 12015
What is the best way to set the href
attribute of the <a>
tag at run time using jQuery?
Also, how do you get the value of the href
attribute of the <a>
tag using jQuery?
Upvotes: 202
Views: 337544
Reputation: 92377
Small performance test comparision for three solutions:
$(".link").prop('href',"https://example.com")
$(".link").attr('href',"https://example.com")
document.querySelector(".link").href="https://example.com";
Here you can perform test by yourself https://jsperf.com/a-href-js-change
We can read href values in following ways
let href = $(selector).prop('href');
let href = $(selector).attr('href');
let href = document.querySelector(".link").href;
Here you can perform test by yourself https://jsperf.com/a-href-js-read
Upvotes: 2
Reputation:
To get or set an attribute of an HTML element, you can use the element.attr()
function in jQuery.
To get the href attribute, use the following code:
var a_href = $('selector').attr('href');
To set the href attribute, use the following code:
$('selector').attr('href','http://example.com');
In both cases, please use the appropriate selector. If you have set the class for the anchor element, use '.class-name'
and if you have set the id for the anchor element, use '#element-id'
.
Upvotes: 379
Reputation: 11
<style>
a:hover {
cursor:pointer;
}
</style>
<script type="text/javascript" src="lib/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".link").click(function(){
var href = $(this).attr("href").split("#");
$(".results").text(href[1]);
})
})
</script>
<a class="link" href="#one">one</a><br />
<a class="link" href="#two">two</a><br />
<a class="link" href="#three">three</a><br />
<a class="link" href="#four">four</a><br />
<a class="link" href="#five">five</a>
<br /><br />
<div class="results"></div>
Upvotes: 1
Reputation: 2634
In jQuery 1.6+ it's better to use:
$(selector).prop('href',"http://www...")
to set the value, and
$(selector).prop('href')
to get the value
In short, .prop
gets and sets values on the DOM object, and .attr
gets and sets values in the HTML. This makes .prop
a little faster and possibly more reliable in some contexts.
Upvotes: 18
Reputation: 10825
Set the href
attribute with
$(selector).attr('href', 'url_goes_here');
and read it using
$(selector).attr('href');
Where "selector" is any valid jQuery selector for your <a>
element (".myClass" or "#myId" to name the most simple ones).
Hope this helps !
Upvotes: 14