JQuery: check if an object has a class

Trying to check if an object has a class. Seems pretty simple, 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>
+5
source share
2 answers
if $(this).hasClass('selected') {

it should be

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

It would be easy to observe if you looked into the browser error console. :-)

+25
source

include full code in

$(document).ready(function(){

$('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');

});

hope this helps.

0
source

All Articles