0

Im looping through all divs on a page trying to get the entire class name (multile class names on a div) - for now im just console.logging them out but it only outputs the fitst match - There are another 7 on the page (within the containing wrap div) but im only getting the first one - any ideas why.

The Classes are named:

pge-rep-1, pge-rep-2, pge-rep-3 ... pge-rep-8

The code is thus:

            $('#pagePoints div').each(function (index) 
            {
                if ( $(this).hasClass("pge-rep-"+index) ) {
                    console.log( $(this).attr('class') );   
                }
            });

1 Answer 1

0

There can be other elements in the selector which does not have any class that starts with pge-rep-. Hence, it is not necessary that the index matches order of the elements with the specified class. You can try the following way using jQuery.is

$('#pagePoints div').each(function (index) {
    if ( $(this).is('[class*=pge-rep-]')) {
        console.log( $(this).attr('class') );   
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks this one seems to work - all my other attempts used the 'begins with' operator ^ - but i moved away from this syntax as it was getting me nothing. I thought it could find any class amongst multiple class names on the same elements. Cheers thanks for your help
@gone - Glad to help you :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.