5

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>
1
  • 6
    Do you need the parentheses around the if condition? Commented May 18, 2012 at 17:22

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

0

include the 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..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.