1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

hasClass example is not working

Discussion in 'jQuery' started by kayut, Mar 19, 2015.

  1. #1
    Can some one please let me know why this code is not working:?

    **HTML**

    <ul>
    <li class="active">First item</li>
    <li>Second item</li>
    <li>Third item</li>
    <li>Fourth item</li>
    </ul>

    **jQuery**

    $(document).ready(function(){
    if( $("li").hasClass("active") ) {
    $(this).css("color", "red");
    }
    });

    Here's the same example on CodePen:
    http://codepen.io/itsthomas/pen/KwrLNY
    Thanks
     
    Solved! View solution.
    kayut, Mar 19, 2015 IP
  2. #2
    You don't have a $(this) - inside an if-statement. $(this) is assigned inside a function.
    This works: http://codepen.io/anon/pen/zxyqZv - but it's slow and horrible - why don't you just do this in CSS? And just do a class-swap on click or whatever so that the correct item is shown active?
     
    PoPSiCLe, Mar 19, 2015 IP
  3. kayut

    kayut Greenhorn

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #3
    Great!
    Thanks for your help.
    This is just a test as I'm learning jQuery. I don't use it in any project.
    I'm just practicing .hasClass.
     
    kayut, Mar 19, 2015 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #4
    One bit of advice, don't use reserved words as classes, it's confusing as hell...
     
    deathshadow, Mar 23, 2015 IP
  5. kayut

    kayut Greenhorn

    Messages:
    13
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    11
    #5
    Are you talking about "active"?
    Is it a reserved class?
     
    kayut, Mar 23, 2015 IP
  6. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #6
    It's a reserved word in CSS in that :active is a pseudo-state. It would be like making a class named "body" or "h1". It's not invalid, it's just annoying/confusing when reading the code and generally considered bad practice...

    ... at least amongst those who practice code clarity; such trifles meaning nothing to the types who actually think needlessly cryptic and pointless code bloat like jQueery serves a legitimate purpose other than making websites slower loading and harder to use.
     
    deathshadow, Mar 23, 2015 IP
    digitalpoint likes this.