jQuery: Check if an object has class

css, html, javascript, jquery

Solution

if $(this).hasClass('selected') {

should be

if($(this).hasClass('selected')){

This would have been easily observed when you have had a look into the browser's error console. :-)

Problem

Trying to check if an object has a class. Seems simple enough, but I can't get it to work. Here is my code: Javascript ``` $('ul.nav li').click(function(){ if $(this).hasClass('selected') { alert('This is selected!'); } else { alert('This is not selected!'); } }); $('ul.nav li:first-child').addClass('selected'); ``` HTML ``` <ul class="nav"> <li>Who we work for</li> <li>Articles and interviews</li> <li>Job openings</li> <li>What the #%!$@ is Post Typography?</li> </ul> <ul class="content"> <li>This is who we work for.</li> <li>These are articles and interviews.</li> <li>These are our job openings.</li> <li>This is some info about Post Typography.</li> </ul> ```

Original source