Necati Necati - 2 months ago 8x
Javascript Question

How to find a div with part of a class name and get remaining part of that class name?

There are several divs on my page with classes

, etc.
What JavaScript or jQuery code can I use to get the number "2" (ie. the number that appends the first matching widget)?

Note: If I were to write this question again, I would change the order of these class names and ask for a way to get "8" in order to avoid giving the impression that I want the smaller number.

$( "[class*='my_widget']" ).each ( function () {
    var elClasses = $( this ).attr ( 'class' ).split ( ' ' );

    for ( var index in elClasses ) {
        if ( elClasses[index].match ( /^my_widget-\d+$/ ) ) {
            var classNum = elClasses[index].split ( '-' )[1];
            alert ( classNum );
} );

Use the "attributeContains" selector to get all elements that have a class my_widget-*, and then loop trough all the classes the element has searching for you class. Once you find it, extract the number part.