Home > Back-end >  Add class to specific elements based on its content
Add class to specific elements based on its content

Time:06-28

I'm trying to add a specific class to a list item depending on its description. But when I add the script below, it adds it to all the list items, and not just those having that specific description.

List items with description "red" should get the class "red", list items with the description "blue" should get the class "blue".

jQuery(document).ready( function($){
    if ($('.tax-desc:contains("red")')) {
        $(".taxonomy-list-item").addClass("red");
    }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
      <div >
          <div >
              <a href="#">Category 1</a>
          </div></div><div >Red</div>
  </div>
</div>
<div >
  <div >
      <div >
          <div >
              <a href="#">Category 2</a>
          </div></div><div >Blue</div>
  </div>
</div>

CodePudding user response:

You don't need an if statement. Use the :has() selector to select the elements with this descendant.

:contains() is case-sensitive, so you need Red rather than red there.

jQuery(document).ready(function($) {
  $('.taxonomy-list-item:has(.tax-desc:contains("Red"))').addClass("red");
});
.red {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  <div >
    <div >
      <div >
        <a href="#">Category 1</a>
      </div>
    </div>
    <div >Red</div>
  </div>
</div>
<div >
  <div >
    <div >
      <div >
        <a href="#">Category 2</a>
      </div>
    </div>
    <div >Blue</div>
  </div>
</div>

  • Related