vlad
vlad

Reputation: 1631

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.

Upvotes: 7

Views: 20209

Answers (4)

Luss Sh
Luss Sh

Reputation: 39

If we are looking for the tag 'a' with dynamical class name, for ex. - StoryBlock_storyLink__5nXw8, then we can use both selectors:

    const a_list = $('a[class*="StoryBlock"]');
    const a_list0 = $('a[class*=StoryBlock]');

Upvotes: 0

georg
georg

Reputation: 215029

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

Upvotes: 8

Felix Kling
Felix Kling

Reputation: 816960

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

Upvotes: 3

Ayyappan Sekar
Ayyappan Sekar

Reputation: 11475

try this,

var names = $('[class*=toaster]').attr('class').split(' ');
var className;
$.each(names, function(){
if (this.toLowerCase().indexOf("toaster") >= 0)
    className = this;
    })
console.log(className);

fiddle is here. You can also have className as an array and push the matched class names to it.

Upvotes: 3

Related Questions