Home > Back-end >  How to work with hasClass in JQuery and add a class to the found values?
How to work with hasClass in JQuery and add a class to the found values?

Time:03-12

In JQuery, after doing the search with hasClass(), how do I add a class to the elements found? With $(this)?

In the example below that I tried to reproduce to explain my question, I searched with hasClass() for elements that have the filter1_1 or filter2_2 class and added a class to paint them in another color, that is, only the News 3 3 should not be painted, what is the correct way to work?

function filter(){
  if($('.news').hasClass('filter1_1') || $('.news').hasClass('filter2_2')){
    $(this).addClass('paint_news');
  }
}
filter();
.paint_news{
  color: #d71f0b;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
  News 1 2
</div>
<div >
  News 1 1
</div>
<div >
  News 3 3
</div>

CodePudding user response:

This will not work... your this is not pointing to the element you desire.

It will be easier to let jQuery do the selecting like this:

function filter() {
  $('.news.filter1_1').addClass('paint_news');
  $('.news.filter2_2').addClass('paint_news');
}

If you want to iterate over the news element, use each like this:

function filter() {
  $('.news').each(function() {
    if($(this).hasClass('filter1_1') || $(this).hasClass('filter2_2')){
      $(this).addClass('paint_news');
    }
  }
}

By the way, you can also regex the hasClass for multiple classes like this:

if($(this).attr('class').match(/filter1_1|filter2_2/)){
  • Related