I found the marked answer wasn't sufficient for me. It states that getting the hash from the URL has huge security flaws but offers no real way of combatting it. There are ways out there of sanitizing the URL if you want to go that route, but if you're simply trying to show()
a container, or apply some CSS/classes to the hash-matching ID container, then there's a much simpler way...
Introducing the :target
selector.
The :target
pseudo-class represents the unique element that has a matching id to the URL's fragment, meaning you can apply JS to it by simply doing something like:
$(':target').show();
Or in my case, just un-hiding the element I want with CSS only:
:target {
display: block;
}
I know the OP's answer is almost exactly 13 years old, but this is a significantly easier and more secure way of achieving the same effect without dealing with getting the URL, splitting it up, sanitizing it - and hell, you can even avoid JS altogether with this method.
And yes, the :target selector is well-supported
'ul#foo:first'
doesn't make sense since IDs must be unique, therefore adding:first
to the selector is redundant, unless you're duplicating IDs which is invalid. Note that even a decade ago, repeated IDs were still invalid. – Slambang