Reputation: 63
I am quite new to JQuery.
I would like to get the value of an anchor from a href with JQuery.
If I'd have the following example, how could i get the value "5" from the href with JQuery?
<a href="user/showUsers#5">User 5</a>
Thanks in advance
-James
Upvotes: 6
Views: 751
Reputation: 5747
If you want to get the numbers given that the URL always follow the same structure try this out,
$(document).ready(function()
{
var number = $("a").attr("href").match(/#([0-9]+)/)[1];
alert(number);
});
Upvotes: 1
Reputation: 13155
If you're going to use this in several places or if you just want a cleaner code I suggest you take a look at this URL parser.
After you've installed it you just use it like this:
var anchor = $.url('http://yoursite.com/user/showUsers#5').attr('anchor');
Upvotes: 0
Reputation: 791
This will bring all the anchor tags with some linked href value
$('a[href*="#"]').each(function(){
if(this.href.split('#').length>1 && this.href.split('#')[1] != ""){
console.log(this.href.split('#')[1]);
}
});
Upvotes: 0
Reputation: 4114
var id = $(this).attr("href").split("#");
id = id[id.length - 1];
Upvotes: -1
Reputation: 1588
Assumint that there will no more occurance of '#'.
<script type="text/javascript" language="javascript">
function GetAnchorValue(CurrCtrl)
{
var hrefText = $(CurrCtrl).attr("href");
var RequiredValue;
if(hrefText.indexOf("#") != -1)
{
RequiredValue = hrefText.split("#")[1];
}
}
</script>
html tag will be
<a href="user/showUsers#5" onclick="return GetAnchorValue(this);">Test Anchor</a>
Upvotes: -1
Reputation: 17380
These are called "Hash". Say your link had an id, you could get it like this:
document.getElementById("link").hash;
This would still give you the "#", but you can easily replace it:
document.getElementById("link").hash.replace("#","");
Good luck!
Upvotes: 1
Reputation: 1075805
First you get the href
, and then you get the part after the first #
:
var href = $("selector_for_the_link").attr('href'),
index = href.indexOf('#'),
anchor = href.substring(index + 1);
Upvotes: 0
Reputation: 15616
Use the following:
var id = $('a').attr('href').split('#');
id = id[id.length - 1];
Upvotes: 2