MohamedKadri
MohamedKadri

Reputation: 627

select one class from classes within the same attribute

I have some elements that when clicked will fire some action and select the "class" attribute.

in jQuery it's simple by using $(this).attr('class')

but the problem is that when we want to select one class from multiple classes like when we have for example:

<a href="#" class="class1 class2"></a>

and we want to get only the first class (class1) because when we use this: $(this).attr('class') we will get "class1 class2" as a result.

any idea?

Upvotes: 1

Views: 1857

Answers (3)

Jared
Jared

Reputation: 861

Had this issue today. Came up with a slightly different solution to deal with not knowing the order of the classes.

Still making the assumption that the class name (or some of it) is known I used a regular expression.

Get the list of classes as a string

var classList = $(this).attr('class');

returns something like "class-1 class-2 my-special-class-1 class-4"

var pattern = /\bmy-special-class-[0-9]+\b/;

In this case I want to find the class any classes that start with "my-special-class-" and end in a number

var matchResult = classList.match(pattern);

Check to see if there is a match(es). In my case I know there is only going to be one class with a number (that I dont know) at the end. I want to use this for a jquery call so I attached the "." to the string

if (matchResult) {
   var foundClass = "." + matchResult[0]; // assuming one class (loop for more)
   var elementsWithClass = $(foundClass);
}

Upvotes: 0

David Tang
David Tang

Reputation: 93694

To get the first class:

$(this).attr('class').split(' ')[0];

However, the idea of classes is that they are unordered, hence there's no jQuery method to do this directly. You may wish to include a data- attribute instead:

<a href="#" class="class2" data-target="someId"></a>

With jQuery 1.4.3+ you can directly access the data-target attribute with:

$(this).data('target');

Upvotes: 2

fl3x7
fl3x7

Reputation: 3803

Not sure if their is a way to do this in jquery but i would just get the classes and then just use a split function and take the first item in the split array

$(this).attr('class')// which happens to have "class1 class2" in it

var mySplitResult = myString.split(" ");
mySplitResult[0] // should be "class1"

hope this helps

EDIT->> seems box9 beat me to it. nice work :)

Upvotes: 1

Related Questions