jQuery - get the first class only from a element

JavascriptJqueryClass

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

You need to split that into an array:

console.log(jQuery('selector').attr('class').split(' ')[0]);

Solution 2 - Javascript

var first = jQuery.attr('class').split(" ")[0];

Solution 3 - Javascript

You can use the following to get the first class only from an element:

var firstClass = jQuery('selector')[0].classList[0]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavascriptSarfrazView Answer on Stackoverflow
Solution 2 - JavascriptgblazexView Answer on Stackoverflow
Solution 3 - JavascriptjackotonyeView Answer on Stackoverflow