JQuery adds a class if another class has this class in a loop

$(document).ready(function() {
  if ($("#grid .media-box").hasClass("brand1")) {
    $("#grid .media-box-content").addClass("brand01")
  };
}
});

and in the network div

<div id="grid">
  <?php foreach($data as $items) { ?>
  <div class="media-box video <?php  echo $items->brand; ?> <?php  echo $items->country; ?>">
    <div class="media-box-image">
      <div data-width="240" data-height="168" data-thumbnail="gallery/thumbnails/thumb-2.jpg"></div>
      <div data-type="iframe" data-popup="https://www.youtube.com/watch?v=5guMumPFBag" title="Psico dell consecteture"></div>
      <div class="thumbnail-overlay">
        <i class="fa fa-video-camera mb-open-popup"></i>
        <a href="#"><i class="fa fa-link"></i></a>
      </div>
    </div>
    <div class="media-box-content">
      <div class="media-box-title">Psico dell consecteture</div>
      <div class="media-box-date">
        <?php echo $items->country; ?></div>
      <div class="media-box-text">Lorem ipsum dolor sitam psico.</div>
      <div class="media-box-more"> <a href="#">Read more</a> 
      </div>
    </div>
  </div>
  <?php } ?>
</div>

CSS

.media-box {
  font-size: 13px;
}
.brand01 {
  background: blue !important;
}
.media-box-content {
  padding: 20px;
  position: relative;
  color: rgb(51, 51, 51);
  line-height: 17px;
}

The above code does not work for me.

 <?php  echo $items->brand; ?> <?php  echo $items->country; ?>" >

extracts 2 classes for diving from the database.

+4
source share
3 answers
$("#grid .media-box.brand1").find(".media-box-content").addClass("brand01")

Your code will add a class brand01to all .media-box-contentif condition true.

+1
source

There is no need to use the if condition, you can use .toggleClass()arg with the second function as a function that returns a boolean like true/false:

$(document).ready(function() {
    $("#grid .media-box-content").toggleClass("brand01", function(){
       return $(this).closest(".media-box").hasClass("brand1");
    });
});

, .media-box-content .media-box, true, , false .

0

Use it, it will work

$(document).ready(function() {
    $("#grid .media-box").each(function(index, element) {
        if ($(this).hasClass("brand1")) {
            $(this).children(".media-box-content").addClass("brand01")
          }
    });

});
0
source

Source: https://habr.com/ru/post/1620687/


All Articles