watzon
watzon

Reputation: 2549

I want to get part of the class of a clicked element in jQuery

So, I have a function like this:

$('a.tdt-btn-*').click(function() {
            var class = $(this + "[class^=tdt-btn-*]"); // Need more here

            console.log(class);
        });

What I want to do is get the value of the wildcard part at the end. How could I do this?

Upvotes: 0

Views: 70

Answers (2)

acdcjunior
acdcjunior

Reputation: 135762

Only one class:

Try this (class is a reserved word, so I'm using clazz):

 $('a[class^="tdt-btn-"]').click(function() {
        var clazz = $(this).attr('class').replace('tdt-btn-','')
        console.log(clazz);
 });

Demo fiddle

Multiple CSS classes:

It will take the first occurrence of the tdt-btn-*.

$('a[class*="tdt-btn-"]').click(function() {
    var clazz = $(this).attr('class').match(/(tdt-btn-)(.+?)(?=(\s|$))/)[2];
    console.log(clazz);
});

Demo fiddle

Upvotes: 1

David Thomas
David Thomas

Reputation: 253318

I'd suggest:

$('a[class*=tdt-btn-]').click(function() {
    var elClasses = this.className.split(/\s+/),
        elClassWildcard;
    for (var i = 0, len = elClasses.length; i < len; i++){
        if (elClasses[i].indexOf('tdt-btn-') === 0) {
            elClassWildcard = elClasses[i].replace('tdt-btn-', '');
        }
    }
    console.log(elClassWildcard);
});

JS Fiddle demo.

Incidentally, class is a reserved word in JavaScript and should, or can, not be used as a variable name (I believe an error is thrown if you do so).

References:

Upvotes: 1

Related Questions