How can I do this:
I have object that has multiple classes. My goal is to get class name that has string(e.g. 'toaster') in it (or starting with that string) and put it in variable.Note that I know only the beggining of class name and I need to get whole.
e.g. <div class="writer quite-good toaster-maker"></div>
I have this div as my jQuery object, I only need to put class name toaster-maker
in variable className
;
Again I don't need to select object! I only need to put class name in variable.
A regular expression seems to be more efficient here:
classNames = div.attr("class").match(/[\w-]*toaster[\w-]*/g)
returns all class names that contain "toaster" (or an empty array if there are none).
So, assuming you already have a jQuery object with that div, you could get the value of the class
attribute, split the string into the class names, iterate over them and see which one contains toaster
:
var className = '';
$.each($element.attr('class').split(/\s+/), function(i, name) {
if (name.indexOf('toaster') > -1) { // or name.indexOf('toaster') === 0
className = name;
return false;
}
});
jQuery doesn't provide an specific function for that.
If you have multiple elements for which you want to extract the class names, you can use .map
:
var classNames = $elements.map(function() {
$.each(this.className.split(/\s+/), function(i, name) {
if (name.indexOf('toaster') > -1) { // or name.indexOf('toaster') === 0
return name;
}
});
}).get();
classNames
will then be an array of class names.
In browser which support .classList
, you could also use $.each(this.classList, ...)
instead of $.each(this.className.split(/\s+/), ...)
.
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