Getting URL hash location, and using it in jQuery
For those who are looking for pure javascript solution
document.getElementById(location.hash.substring(1)).style.display = 'block'
Hope this saves you some time.
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.
You can use the location.hash
property to grab the hash of the current page:
var hash = window.location.hash;
$('ul'+hash+':first').show();
Note that this property already contains the #
symbol at the beginning.
Actually you don't need the :first
pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.
In case you want to get the hash from an URL string, you can use the String.substring
method:
var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'
Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.
location.hash is not safe for IE , in case of IE ( including IE9 ) , if your page contains iframe , then after manual refresh inside iframe content get location.hash value is old( value for first page load ). while manual retrieved value is different than location.hash so always retrieve it through document.URL
var hash = document.URL.substr(document.URL.indexOf('#')+1)