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?
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.
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.
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).
You need to split
that into an array:
console.log(jQuery('selector').attr('class').split(' ')[0]);
var first = jQuery.attr('class').split(" ")[0];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With