1

I am trying to apply the following jQuery click function but for some reason I 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.

0

4 Answers 4

4

How about this?

$("ul.menu li a").click(function(){
   $(".topm").attr('id', '');
   $(this).attr("id" , "current" );
});
Sign up to request clarification or add additional context in comments.

1 Comment

@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.
0

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.

Comments

0

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');
});

Comments

0

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" );
    });

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.