I have js that caches classes that's name starts with "whatever-",
$('[class^="whatever-"], [class*=" whatever-"]')
but what I want now to do is get the rest of the name, for example in case of "whatever-9" I want to get "9", I don't know how to do it, can you help me?
jQuery hasClass() Method The hasClass() method checks if any of the selected elements have a specified class name. If ANY of the selected elements has the specified class name, this method will return "true".
The hasClass() is an inbuilt method in jQuery which check whether the elements with the specified class name exists or not. Syntax: $(selector). hasClass(className);
$ is another, which is just an alias to jQuery . $$ is not provided by jQuery. It's provided by other libraries, such as Mootools or Prototype.
Try this
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 for the case when there is more than 1 class. There may be cleaner ways of doing this by using filter
method and a bit of regex
A 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(' '));
});
Map demo
Maybe there are better ways, but this works. Check 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);
});
This is assuming you just have one class in the elements you are targeting with your selectors.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With