jay stephens jay stephens - 2 months ago 8
HTML Question

alert when multiple elements with the same class name have an added class

I need an alert to show up when all elements have had a class added to them

html

<ul class="container">
<li class="box"> </li>
<li class="box"> </li>
<li class="box"> </li>
</ul>


jquery -

$(document).ready(function() {
$('.box').click(function() {
$(this).addClass('Boxaddedclass');
});
});


After each box is clicked, a class of 'Boxaddedclass' is added to each list with the class of '.box'.

jquery -

$(document).ready(function () {
$(".box").click(function () {
if($(".box").hasClass("Boxaddedclass")) {
alert('all boxes have the added class')

}
});


At the moment, after I click each individual Box class, an alert comes up each time, I need the alert to appear when all of them have the added class rather than individually. Any way around this?

Answer

$(".box.Boxaddedclass") selector could be used to check .box elements also has .Boxaddedclass class.

Only using $(".Boxaddedclass") will not consider .box elements having Boxaddedclass class!

$('.box').click(function() {
  $(this).addClass('Boxaddedclass');
});

$('button').on('click', function() {
  var boxCount = $(".box").length;
  var addedBoxClass = $(".box.Boxaddedclass").length;
  if (boxCount === addedBoxClass) {
    alert("All boxes have added the class");
  } else {
    alert('Not yet!')
  }
});
.Boxaddedclass {
  background: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<ul class="container">
  <li class="box">Content...</li>
  <li class="box">Content...</li>
  <li class="box">Content...</li>
</ul>
<div class="Boxaddedclass">Other content not having `box` class but `Boxaddedclass`</div>
<br>
<button>Check</button>

Comments