0

I have the following two functions that do the same thing, any way I can combine these two functions into a single function?

$(document).ready(function(){
    $("#nav li").click(function(e) {
        e.preventDefault();
        $("#nav li").removeClass("current_page_item");
        $(this).closest("li").addClass("current_page_item");
    });
    $("#overlay li").click(function(e) {
        e.preventDefault();
        $("#overlay li").removeClass("current_page_item");
        $(this).closest("li").addClass("current_page_item");
    });
});

Thanks,
Josh

1
  • why not just add the same class to both the ul then you can target that class - after all that's what class names are meant, targeting like elements (or just add the class to the li and target them directly - will make your jquery selector a lot more efficient) Commented Mar 18, 2019 at 17:11

1 Answer 1

5

You could use a pair of selectors combined with a comma. The matching elements for both selectors will be returned:

$("#nav li, #overlay li").click(function(e) {
    e.preventDefault();
    $(this).closest('#nav, #overlay').find('li').removeClass("current_page_item");
    $(this).closest("li").addClass("current_page_item");
});

To deselect the other elements when this is clicked, find the ancestor matching the container ID (nav or overlay), and remove the current_page_item class from the descendant li elements.

Sign up to request clarification or add additional context in comments.

2 Comments

$(this) to $(this).closest('#nav, #overlay').find('li') should allow you to keep the logic and remedy the not changing siblings. Edit: and the closest on the last command is pointless as the this is an li.
This works great! I tried the comma separating the selectors on the function, but missed it on the this.closest...thanks!

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.