Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Check if an object has class

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>
like image 458
colindunn Avatar asked May 18 '12 17:05

colindunn


1 Answers

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. :-)

like image 137
YMMD Avatar answered Oct 09 '22 12:10

YMMD