Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript / jQuery : Select class name that contains word

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.

like image 576
vlad Avatar asked Dec 11 '22 12:12

vlad


2 Answers

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).

like image 140
georg Avatar answered Jan 05 '23 00:01

georg


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+/), ...).

like image 40
Felix Kling Avatar answered Jan 05 '23 01:01

Felix Kling