jay stephens jay stephens - 2 months ago 6
HTML Question

Even Listener for .length

At the moment I have a script that counts the amount of classes in the document, however, I'm using another jquery script to '.remove' the classes when clicked, but the .alerts count remains the same. I'm assuming this is because the document needs an event listener but can't seem to get it working.

html -

<ul>
<li class="alert"> </li>
<li class="alert"> </li>
<li class="alert"> </li>
</ul>

<div class="counter">3</div>

document.getElementsByClassName("counter")[0].textContent
=document.querySelectorAll("ul > .alert").length;


It displays the correct amount, but doesn't change when they're removed by jquery, any help would be appreciated thanks.

Answer

You can call a function which updates current .length of elements when element is removed

$(function() {

  function count() {
    $(".counter").html($(".alert").length)
  }

  count();

  $(".alert").click(function() {
    $(this).remove();
    count();
  });

  $("button").click(function() {
    $(".alert").eq(+$(this).prev("input").val()).remove();
    $(this).prev("input").attr("max", $(".alert").length)
    .val($(".alert").length -1)
    count()
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="alert">click</li>
  <li class="alert">click</li>
  <li class="alert">click</li>
</ul>

<div class="counter"></div>
<input type="number" min="0" max="2" value="2">
<button>remove alert</button>