Live get number of spans inside div

WordPress has a div .tagchecklist with spans (tags) inside it.
I’m trying to count these spans but I always get 0.

My code is the following:

Read More
jQuery( document ).ready( function() {
  console.log( jQuery( '.tagchecklist > span' ).length );
})

The .tagchecklist div is updated with spans if I add a new tag or select it from the list, but the console always output 0. Is there any way to live-check it?

<div class="tagchecklist">
  <span><a id="faq_section-check-num-0" class="ntdelbutton">X</a>&nbsp;ecr</span>
  <span><a id="faq_section-check-num-1" class="ntdelbutton">X</a>&nbsp;ecrrec</span>
  <span><a id="faq_section-check-num-2" class="ntdelbutton">X</a>&nbsp;ercerce</span>
</div>

<p id="tagcloud-faq_section" class="the-tagcloud">
    <a href="#" class="tag-link-4" title="2 topics" style="font-size: 14.3pt;">Account</a>
    <a href="#" class="tag-link-2" title="4 topics" style="font-size: 22pt;">Introduction</a>
    <a href="#" class="tag-link-7" title="1 topic" style="font-size: 8pt;">Other</a>
    <a href="#" class="tag-link-3" title="2 topics" style="font-size: 14.3pt;">Pricing &amp; Billing</a>
</p>

Somehow I just did:

jQuery( document ).ready( function() {
  jQuery( '#faq_section' ).on( 'click', '.tagadd, .ntdelbutton, .the-tagcloud > a', function() {
    console.log( jQuery( '.tagchecklist span' ).length );
  } )
})

And it works for adding a tag, but for .ntdelbutton and .the-tagcloud > a it doesn’t update!

Related posts

Leave a Reply

2 comments

  1. One solution is to add it inside the event like:

    $(":button").on("click", function() {
      $(".tagchecklist").append("<span></span");
      console.log($(".tagchecklist > span").length);
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="tagchecklist"></div>
    <input type="button" value="Add span" />