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:
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> ecr</span>
<span><a id="faq_section-check-num-1" class="ntdelbutton">X</a> ecrrec</span>
<span><a id="faq_section-check-num-2" class="ntdelbutton">X</a> 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 & 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!
One solution is to add it inside the
event
like:@Alex’s answer is the ideal place to do what you need. Otherwise, you need to watch for changes to a DOM element, which is answered here: Detect element content changes with jQuery