views:

59

answers:

3

Trying to find the attribute value from a url hash.

// URL
http://url.com/index.html#link

// HTML
<a href="#link" rel="3">Some link</a>

// JS
var anchor = window.location.hash.substring(1);
// Need help finding attribute value from finding the anchor
var attribute = .find('#+anchor').attr('rel'); //this needs to have a value of 3

All help appreciated. Thanks :)

+1  A: 

You can do it using an attribute-equals selector, like this:

$('a[href="'+window.location.hash+'"]').attr("rel")

Or .filter(), like this:

$("a").filter(function() { return this.hash == location.hash; }).attr("rel")

The .hash starting with # will be consistent, so no need to remove/add this back, just use it as-is.

Nick Craver
great. now, how can I get the reverse... find a #hash from a rel?
Jeffrey
@Jeffrey - The same type of selector, for example: `$('a[rel="something"]').attr("href")`
Nick Craver
thanks, that did it
Jeffrey
A: 

Is this what you need?

var attribute = $("a[href='#" + anchor + "']").attr('rel');
John Fisher
+1  A: 
 $('a[href=' + window.location.hash +']').attr("rel");
Jud Stephenson
The extra space will make this not work, you're got an extra descendant selector in there.
Nick Craver
Your right, iPad autocorrect
Jud Stephenson