1

We have a menu that has the following structure below (ul > li > a). We want to be able to find all <a> that have a css class starting with color-- and bkg--.

I know I can get all the grandchildren by doing $(element).children().children(). Is there an easier way to get all the grandchildren, check if they have the class, and then remove it using jQuery?

What we have tried:

    $(function() {
      var grandChildren = $('#someid > li > a');
      grandChildren.removeClass('[class*="bkg--"]');
      grandChildren.removeClass('[class*="color--"]');
    });
    .bkg--black {
      background-color: black;
    }
    .bkg--white {
      background-color: white;
    }
    .bkg--red {
      background-color: red;
    }
    .bkg--blue {
      background-color: blue;
    }

    .color--white {
      color: white;
    }
    .color--black {
      color: black;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<ul id='someid'>
  <li>
    <a class="bkg--black color--white" href="#">Some path 1</a>
  </li>
  <li>
    <a class="bkg--white color--black" href="#">Some path 2</a>
  </li>
  <li>
    <a class="bkg--red color--white" href="#">Some path 3</a>
  </li>
  <li>
    <a class="bkg--blue color--white" href="#">Some path 4</a>
  </li>
</ul>
usernameabc
  • 662
  • 1
  • 10
  • 30

1 Answers1

0

Yes. Simply use the .find() method and some code from your previous question

jQuery(function($) { // Better DOM ready

  $("#someid").find("a").prop("class", function(i, cls) {
    return cls.replace(/(^|\s)(bkg|color)--\S+/g, '');
  });

});
.bkg--black {
  background-color: black;
}

.bkg--white {
  background-color: white;
}

.bkg--red {
  background-color: red;
}

.bkg--blue {
  background-color: blue;
}

.color--white {
  color: white;
}

.color--black {
  color: black;
}
<ul id='someid'>
  <li>
    <a class="bkg--black color--white" href="#">Some path 1</a>
  </li>
  <li>
    <a class="bkg--white color--black" href="#">Some path 2</a>
  </li>
  <li>
    <a class="bkg--red color--white" href="#">Some path 3</a>
  </li>
  <li>
    <a class="bkg--blue color--white" href="#">Some path 4</a>
  </li>
</ul>


<script src="//code.jquery.com/jquery-3.1.0.js"></script>

Pro tip:

'[class^="bkg--"]' is not enough in the case you have class="foo bkg--red" since ^= means Starts with;but it starts with foo.
instead use:

'[class^="bkg--"], [class*=" bkg--"]'

Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313