jQuery can’t find element

I keep having an annoying problem with jQuery where it doesn’t appear to be able to find an element.  This is actually a silly mistake on my part.  eg.

<div id=”msg”>Hello World</div>

<script type=”text/javascript”>

$(‘msg’).hide();

</script>

This is actually not a bug in jQuery at all – it is functioning correctly.  It should be $(‘#msg’).show(); since jQuery uses CSS style selectors.  $(‘msg’) would be looking for a tag named msg (ie. <msg>).

I figure that a lot of other people make the same mistake as it is easy to think of $() as being like document.getElementById, when it isn’t!  The reason that I’ve bothered posting about it is that I’ve ended up spending quite a bit of time trying to spot what I’ve done wrong!

Leave a Reply