简体   繁体   中英

Open parent dropdown if child contains active class?

I have a simple dropdown with checkboxes inside. I have an active class on the child LI elements which simulates a checked box. I want to check if the dropdown has a child li element with an active class. If it does i want the dropdown active class to be added automatically on page load.

Here is my JS Fiddle

https://jsfiddle.net/p5jzgdqn/3/

Here is my jQuery

 //make list a dropdown $(".category-filters-section-title").click(function() { $(this).siblings("ul.category-filters-area-list").toggleClass("filter-dropdown-active"); }); //open dropdown if any of the li children contains the class "active-filter" $( document ).ready(function() { $(".category-filters-area-section").each(function() { if ($(this).has(".active-filter").length) { // find the parent and add class ONLY if the "IF" is true $(this).closest("ul.category-filters-area-list").addClass("filter-dropdown-active"); } }); });

I need to target (this) element starting at the parent <ul> element because there is going to be multiple dropdowns. But one should be okay for this example.

Thanks for any help!

Couple of things stopping your code from working

$(".category-filters-area-section").each(function() {
  if ($(this).has(".active-filter").length) {

needs to be

$(".category-filters-area-section").each(function() {
  if ($(this).has(".active-filter")) {

without.length as .has returns a boolean. You could have used

$(".category-filters-area-section").each(function() {
  if ($(this).find(".active-filter").length) {

Next:

    // find the parent and add class ONLY if the "IF" is true
    $(this)
      .closest("ul.category-filters-area-list")
      .addClass("filter-dropdown-active");

here, this refers to each of the .category-filters-area-section but in your HTML (in the fiddle), the -section is the parent of the -list , so .closest() won't find it, so this could be:

    // find the parent and add class ONLY if the "IF" is true
    $(this)
      .find("ul.category-filters-area-list")
      .addClass("filter-dropdown-active");

to get the.list that is a child of the.section. However, this will cause problems if you have multiple.list entries in each.section (hard to tell as your fiddle only had 1).


Alternatively, you can find the li.active and work back from there:

  $(".category-filters-area-list li.active-filter")
    .parent()
    .addClass("filter-dropdown-active");

Updated fiddle: https://jsfiddle.net/2Lx8op6f/

$(".advanced-filter").each(function(index) {
  if($(this).hasClass('active-filter'))
  $(this).parent('ul').addClass('filter-dropdown-active');
});

Oh i should look up instead of look down.

Cheers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM