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
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?
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.
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.