Rudolf Lamprecht Rudolf Lamprecht - 3 years ago 72
jQuery Question

How to select part of a specific css class name out of multiple classes

Given the following HTML markup:

<div id="my-id" class="my-class items-5"/>

How can I extract the
from the class attribute, if the
is generated dynamically?
I could probably do a split on the
' '
and reference the index of the
on the second index, but this seems so long winded:

var count = $("#my-div").attr("class").split(' ')[1].split('-')[1];

Answer Source

Another solution for a fixed markup that you can't change, and assuming that the relevant class is always items-number is to split by items-, and then get the first word after it:

var count = $("#my-id").attr("class").split('items-')[1].split(' ')[0];

var count2 = $("#my-id2").attr("class").split('items-')[1].split(' ')[0];
<script src=""></script>
<div id="my-id" class="my-class items-5"/>
<div id="my-id2" class="my-class items-23 another-class"/>

This would also work for more classes and different orderings.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download