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

There are several sections on my page with the 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 the first matching widget adds)?

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

+4
source share
5 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 the elements that have the my_widget-* class, and then loop through all the classes the element searches for your class. Once you find it, remove the number.

+7
source

This should do the trick:

 $("[class^='my_widget']").each(function() { var classParts = $(this).attr('class').split('-'); var number = classParts.pop(); }); 

Note that it will only work if a special class exists, otherwise you will get something like 8 otherclass .

+1
source

JS main approach:

 <div id="x" class="widget-2 lang-ζ—₯本θͺž">foo</div> function Element_getClassArgument(el, name) { var classes= el.className.split(' '); var prefix= name+'-'; for (var i= classes.length; i-->0;) if (classes[i].substring(0, prefix.length)==prefix) return classes[i].substring(prefix.length); return null; } Element_getClassArgument(document.getElementById('x'), 'widget'); // 2 

If you want to include whitespace or a hyphen in the name, you will have to enter some kind of coding scheme, for example encodeURIComponent . But often you can leave without it.

A wrapper in something with $ in the name remains as an exercise for the reader. :-)

+1
source

If you want to get DIV elements with class my_widget-2 , use this selector:

 $("div.my_widget-2") 

But if you want to get all DIV elements with a class of the form my_widget-N , where N is an arbitrary number, try the following:

 $("div[class]").each(function() { var matches = this.className.match(/(?:^|\s+)my_widget-(\d+)(?:\s+|$)/g); if (matches !== null) { alert(matches); } }) 
0
source

Try element.attr('class').match(/my_widget-(\d+)/)[1]

It should return the column number as a string, so just run parseInt () on it

0
source

All Articles