Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 my_widget-2, my_widget-8, 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.

like image 447
Necati Avatar asked Jan 05 '10 13:01

Necati


1 Answers

$( "[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 );
            break;
        }
    }
} );

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.

like image 171
Jan Hančič Avatar answered Oct 19 '22 23:10

Jan Hančič