Getting URL hash location, and using it in jQuery

Robbie White picture Robbie White · Nov 30, 2009 · Viewed 239.9k times · Source

I'd like to get the value after a hash in the URL of the current page and then be able to apply this in a new function... eg.

The URL could be

www.example.com/index.html#foo

And I would like to use this in conjunction with the following piece of code

$('ul#foo:first').show();

I'm kinda assuming/hoping there is some way of grabbing this, and turning it into a variable that I can then use in the second piece of code.

Answer

Christian C. Salvadó picture Christian C. Salvadó · Nov 30, 2009

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.