Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add class to specific elements based on its content

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 class="taxonomy-list-item">
  <div class="tax-details">
      <div class="tax-name">
          <div class="tax-title">
              <a href="#">Category 1</a>
          </div></div><div class="tax-desc">Red</div>
  </div>
</div>
<div class="taxonomy-list-item">
  <div class="tax-details">
      <div class="tax-name">
          <div class="tax-title">
              <a href="#">Category 2</a>
          </div></div><div class="tax-desc">Blue</div>
  </div>
</div>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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 class="taxonomy-list-item">
  <div class="tax-details">
    <div class="tax-name">
      <div class="tax-title">
        <a href="#">Category 1</a>
      </div>
    </div>
    <div class="tax-desc">Red</div>
  </div>
</div>
<div class="taxonomy-list-item">
  <div class="tax-details">
    <div class="tax-name">
      <div class="tax-title">
        <a href="#">Category 2</a>
      </div>
    </div>
    <div class="tax-desc">Blue</div>
  </div>
</div>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading