I’m trying to find an element with the class “active” and then echo what other classes it has, and only select the start of the string.
HTML:
<div class="cmButtons">
<ul>
<li class="cmAuto_btn a active">Auto BTN</li>
<li class="cmPro_btn a">Pro BTN</li>
<li class="cmFocus_btn a">Focus BTN</li>
<li class="cmBright_btn a">Bright BTN</li>
<li class="cmLow_btn a">Low BTN</li>
<li class="cmMotion_btn a">Motion BTN</li>
<li class="cmCustom_btn a">Custom BTN</li>
</ul>
</div>
CSS:
#result{background:#EEE;border:1px solid #CCC;margin:20px 0;height:30px;line-height:30px;width:500px;}
Javascript (with jQuery):
if($('.cmButtons ul li').hasClass("active")){
var activeLi = $(this).attr("class");
$('#result').html(activeLi);
}
So, based on the fiddle;
The active element is: <li class="cmAuto_btn a active">Auto BTN</li>
jQuery should output the class as: cmAuto_btn a active
jQuery should then modify the string to render as cmAuto_btn
How can I do this?
You need to iterate over the set of matched elements with
each. You can then split the class names on spaces, and get the first element of the resulting array:Here’s an updated example.
And here’s an alternative, due to comments below (still using
eachin case there are multiple elements with classactive):You should probably use this one, unless you also need to do something with elements that do not have the
activeclass, in which case you can use the above example with anelseblock.