Ben Racicot
Ben Racicot

Reputation: 5903

How to test for and count dynamically numbered classnames with JavaScript

I have my object like so:

var text = document.getElementsByClassName('decode-text')[0];

It is a list of html elements that look like:

<div class="decode-text">
    <div class="cycleText">
        <div class="cycle-0"> 
            <div class="text-animation">hey</div>
        </div>
        <div class="cycle-1"> 
            <div class="text-animation">you</div>
        </div>      
        <div class="cycle-2"> 
            <div class="text-animation">guys</div>
        </div>
    </div>
</div>

I will just use indexof but want to understand why .contains returns false?

text.classList.contains('cycleText'); = false // why

Also any recommendations on getting the number of 'cycle-*' class names in this node list?

Upvotes: 1

Views: 205

Answers (2)

TimoStaudinger
TimoStaudinger

Reputation: 42460

classList is a list of classes assigned to the current DOM element, and does not include the classes of its children.

The only entry of the list is decode-text.

Upvotes: 1

pstenstrm
pstenstrm

Reputation: 6489

You can achieve this using css attribute selectors. The ^ means "starts with":

document.querySelectorAll('[class^="cycle-"]');

Upvotes: 4

Related Questions