javascriptjqueryclassvariablesselect

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.


Solution

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