Bongbong
Bongbong

Reputation: 67

jQuery: How to combine these two statements into one?

if($(this).parents("ul").closest("#menu-main").length){
  var parent = $(this).parent();

  parent.addClass("current");

  if(parent.hasClass("more-options")){
    $(parent).siblings(".more-options-page").addClass("current").show();
  }
}

Instad of repeating the addClass() with an if statement, how can I add show() to the parent with class "more-options" to the first one please?

Upvotes: 0

Views: 144

Answers (1)

Rich O'Kelly
Rich O'Kelly

Reputation: 41757

If you so wished, you could chain all necessary method calls like so (supplying the optional filter to the parent method):

if ($(this).parents("ul").closest("#menu-main").length) {
  $(this).parent().addClass("current");
  $(this).parent(".more-options").show().siblings(".more-options-page").addClass("current").show();
}

Update

Yes it can be done in one line, but isn't entirely readable:

if ($(this).parents("ul").closest("#menu-main").length) {
  $(this).parent().addClass("current").filter(".more-options").show().siblings(".more-options-page").addClass("current").show();
}

Upvotes: 1

Related Questions