Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery - get the first class only from a element

The element looks like this:

<li class="blah active"> ... </li> 

jQuery.attr('class') will return both classes. How can I get only the 1st class ('blah' in this case) with jQuery?

like image 692
Alex Avatar asked Jul 08 '10 13:07

Alex


People also ask

How do I get the class name from one element?

If you want only the first element in the DOM with that class, you can select the first element out of the array returned. var elements = document. getElementsByClassName('className'); var requiredElement = elements[0]; Else, if you really want to select only one element.

How do you target a class in jQuery?

In jQuery, the class and ID selectors are the same as in CSS. If you want to select elements with a certain class, use a dot ( . ) and the class name. If you want to select elements with a certain ID, use the hash symbol ( # ) and the ID name.

How do you select the first element with the selector statement?

The :first selector selects the first element. Note: This selector can only select one single element. Use the :first-child selector to select more than one element (one for each parent). This is mostly used together with another selector to select the first element in a group (like in the example above).


2 Answers

You need to split that into an array:

console.log(jQuery('selector').attr('class').split(' ')[0]); 
like image 115
Sarfraz Avatar answered Sep 18 '22 08:09

Sarfraz


var first = jQuery.attr('class').split(" ")[0]; 
like image 37
25 revs, 4 users 83% Avatar answered Sep 21 '22 08:09

25 revs, 4 users 83%