ngplayground
ngplayground

Reputation: 21617

jQuery get class of an element which has 2 classes

<button class="update vacancy-submit" tabindex="2">Save</button>

$('.vacancy-submit').click(function(){
    var type = $(this).attr('class').not('.vacancy-submit');
    console.log(type);
});

I'm trying to get the class for button into a variable which should say update and not update vacancy-submit

Upvotes: 1

Views: 115

Answers (5)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

After much thinking about this, I would actually suggest you define the following JQuery extension to isolate the problem and make it a bit more reusable:

jQuery.fn.firstClass = function() {
    return this.attr('class') ? this.attr('class').split(' ')[0] : "";
   };

Then you simply have:

$('.vacancy-submit').click(function(){
    var type = $(this).firstClass();
    console.log(type);
});

Updated JSFiddle here: http://jsfiddle.net/TrueBlueAussie/Bh8JT/1/

Has test cases for 0, 1 or more classes.

Upvotes: 0

Sid M
Sid M

Reputation: 4354

Try this to get the name of first class in class attribute

function classname() {
         var myClassName = $('#id').attr('class').split(' ');
        var firstName = myClassName[0];
      }

Upvotes: 0

adeneo
adeneo

Reputation: 318172

If it's always the first class:

$('.vacancy-submit').click(function(){
    var type = this.className.split(/\s+/).shift();
    console.log(type);
});

FIDDLE

Upvotes: 5

Arun P Johny
Arun P Johny

Reputation: 388316

You need to replace the unwanted portion of the class attribute value

var type = $.trim($(this).attr('class').replace('vacancy-submit', ''));

Upvotes: 1

DGS
DGS

Reputation: 6025

The following code will remove vacancy-submit from the string you get.

$('.vacancy-submit').click(function(){
    var type = $(this).attr('class').replace('vacancy-submit','');
    console.log(type);
});

Upvotes: 0

Related Questions