views:

49

answers:

2

Cletus helped my with this really sweet code yesterday: http://stackoverflow.com/questions/2063122/what-javascript-object-am-i-looking-for-click-a-button-it-stays-bold-till-the-n

This takes the class of my li and changes the class. It works great! I'm wanting to extend this so it will also change the class within the a in the li. How do I do that?

Example:

<ul>
 <li class="old_class"><a class="old_class" ...>
 <li class="old_class"><a class="old_class" ...>
 <li class="old_class"><a class="old_class" ...>
</ul>

So when I click the first link it would become:

<ul>
 <li class="new_class"><a class="new_class" ...>
 <li class="old_class"><a class="old_class" ...>
 <li class="old_class"><a class="old_class" ...>
</ul>

As the code is now, the li class changes, but not the a.

The code I'm using:

$(".old_class").click(function() {
  $(".new_class").removeClass("new_class");
  $(this).addClass("new");
});

Thank you! I'm using Jquery...

+2  A: 

Try:

$(".old_class").click(function() {
  $(this).removeClass("old_class");
  $(this).children("a").removeClass("old_class");
  $(this).addClass("new_class");
  $(this).children("a").addClass("new_class");
});
Sbm007
Hi-That worked to change both classes, but it's not toggling the old ones back...This is on a nav-bar type thing where the li and a are changing until a different li and a are clicked and then go back to their old state...
Joel
+2  A: 

Define you ul with a class, say <ul class="nav">...

Then:

var navItems = $('.nav > li');
navItems.click (function () {
    navItems.children ('a').andSelf ()
        .removeClass ('new_class').addCass ('old_class');
    $(this).children ('a').andSelf ()
        .removeClass ('old_class').addClass ('new_class');
});

That said, you don't need any class in the children a - you could refer to them in CSS as simply .new_class a

K Prime
I just realized that myself about being able to just do the .new_class a thing. So much to learn :-D Thanks for your help!
Joel