tags:

views:

40

answers:

5

Hi,

I am trying to apply the following jquery click function but for some reason can't seem to get the selector right, i.e.:

$("ul.menu li a").click(function(){
   $("ul.menu li").find("a").removeAttr("id");
   $(this).attr("id" , "current" );
});

This is my HTML code I am trying to apply it to, i,e,:

        <div id="sidebar">
            <ul class="menu noaccordion">
                <li>
                    <a href="#" id="current" class="topm">Home</a>
                </li>
                <li>
                    <a href="#" class="topm">About Us</a>
                </li>

My aim is to try and set the current menu selected using the id=current.

Any help to get jquery selector correct would be much appreciated.

Thanks.

+3  A: 

How about this?

$("ul.menu li a").click(function(){
   $(".topm").attr('id', '');
   $(this).attr("id" , "current" );
});
Jacob Relkin
sorry Jacob, didn't seem to work.
tonsils
Yes it does : http://jsfiddle.net/5BDD9/
Kaaviar
@Kaaviar - I used Jacob's code but it didn't seem to work for my case, unsure if it's a DOM thing but appreciate your feedback.
tonsils
@tonsils, that's because I edited it again.
Jacob Relkin
@Kaaviar - no worries, didn't realise. thanks.
tonsils
@tonsils : no problem ;)
Kaaviar
A: 

I wouldn't remove the ID of the element. The ID attribute is designed to represent a single element in the DOM. You should really apply this with a class instead:

$("ul.menu li a").removeClass("currentMenu");
$(this).addClass("currentMenu");

So in your example:-

$("ul.menu li a").click(function() {
  $("ul.menu li a").removeClass("currentMenu");
  $(this).addClass("currentMenu");
});

You don't need to use each, as the removeClass action will be applied to each jquery result from the selector.

Andy Robinson
A: 

I would recommend you to use a class name that indicates that a menu is selected instead of id:

<ul>
    <li>
        <a href="#" class="topm selected">Home</a>
    </li>
    <li>
        <a href="#" class="topm">About Us</a>
    </li>
</ul>

Then your click function might look like this:

$('ul a').click(function() {
    $('ul a').removeClass('current');
    $(this).addClass('current');
});
Darin Dimitrov
A: 

$('ul.menu li a').click(function(){
$('.topm').removeAttr('id');
$(this).attr('id','current');
});

Ashin
A: 

Thanks to all for your assistance but I managed to get it going from my original code plus the addition of a .find("a") on the last line, which has solved my problem, i.e.

    $("#sidebar ul.menu li").click(function() {
       $("ul.menu li").find("a").removeAttr("id");
       $(this).find("a").attr("id" , "current" );
    });

Thanks again.

tonsils