JQuery gets the rest of the element's class name, which starts with the string "any-"

I have js that caches classes whose names begin with "whatever -",

$('[class^="whatever-"], [class*=" whatever-"]') 

but what I want to do now is get the rest of the name, for example, in the case of "nothing-9" I want to get "9", I don’t know how to do it, can you help me

+4
source share
3 answers

try it

 var check = "whatever-";        $('[class^="whatever-"], [class*=" whatever-"]').each(function () {   // Get array of class names  var cls = $(this).attr('class').split(' ');      for (var i = 0; i < cls.length; i++) { // Iterate over the class and log it if it matches if (cls[i].indexOf(check) > -1) {       console.log(cls[i].slice(check.length, cls[i].length)); }      }   }); 

This should also work if there is more than one class. There may be cleaner ways to do this using the filter method and the regex bit.

Check feed

Little cleaner using map

 var check = "whatever-"; $('[class^="whatever-"], [class*=" whatever-"]').each(function () { var className = this.className; var cls = $.map(this.className.split(' '), function (val, i) { if (val.indexOf(check) > -1) { return val.slice(check.length, val.length) } }); console.log(cls.join(' ')); }); 

Show demo

+6
source

There may be better ways, but it works. Check out the console.

Demo

 $('[class^="whatever-"], [class*=" whatever-"]').each(function () { var classname = this.className; var classsparts = classname.split('whatever-'); var result = classsparts[1] console.log(result); }); 

It is assumed that you have only one class in the elements that you are targeting with your selectors.

+1
source

Or, if you like a little regex, I would use this because it is just one line.

 $("*").filter(function(){ return /whatever-.+/.test( $(this).attr("class") ) } ); 
0
source

Source: https://habr.com/ru/post/1496283/


All Articles