3

I have been googling, a lot, and found quiet many similar issues around the www but not anything that nails my issue to the ground.

I have a jquery function that get the href attribute from an anchor tag, which is supposed to return this value - #SomeIDHere

On my development environment it works perfectly, but on production it returns the current URI + the #ID. I only need the #ID part to make the rest of the script work as intended.

This is how I get the href, now I only need to split the href value and get the #ID part.

function myFunction(sender) {
    var id = sender.getAttribute('href');
    alert(id);
    // functionallity here...
}

I have tried this solution which was a brilliant start but when I tried implementing it I only got undefined values or javascript errors.

Some of the things I tried:

function myFunction(sender) {
var id = sender.getAttribute('href');
var newID = $(id).search.split('#')[1]; // got an error
alert(id);
// functionallity here...
}

function myFunction(sender) {
var id = sender.getAttribute('href');
var newId = $(id).split('#')[1]; // got an error
// functionallity here...
}

function myFunction(sender) {
var id = sender.getAttribute('href');
var newId = $(sender)[0].search.split('#')[1]; // returned undefined
// functionallity here...
}

Any thought or ideas of how to do this? I'm kind of lost at the moment.

3 Answers 3

8

Use jquery

Then see this if this is your need

<a href="a.php#1">1</a>
<a href="a.php#2">2</a>

Jquery Part

$("a").live("click",function(){
   alert($(this).attr("hash"));
});

Working Example On JsFiddle

Sign up to request clarification or add additional context in comments.

2 Comments

Dude you saved my f'ing day! Thanks so much! This issue have been bugging me for a LONG time!
You should note that this is a new attribute in HTML5: developer.mozilla.org/en/DOM/HTMLAnchorElement. It might not work in every browser.
4

You've already accepted, but without jQuery you can do this:

var url = 'http://news.ycombinator.com/item?id=2217753#blah';

var index = url.lastIndexOf('#');

var hashId = url.substring(index + 1, url.length);

//alert(hashId);

The variable hashId now contains 'blah';

1 Comment

@Ziga - if you use this you should check that index != -1, which is what lastIndexOf returns if the test character is not found.
1

You are mixing jQuery and JavaScript string functions. This should work (if you can be 100% sure that the URL contains #something):

function myFunction(sender) {
    var id = '#' + sender.getAttribute('href').split('#')[1];
    // or `'#' + sender.href.split('#')[1]`
    // or `'#' + $(sender).attr('href').split('#')[1]`

}

1 Comment

Doh! The one thing I didn't try! :-O Thank you :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.