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'
.
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.
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 !
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
<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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With