I’ve selected the following element. What’s the best way to get the class name icon_23123?
<div class="icon icon_23123"></div>
Is there something like [class^=”icon_”] to select attributes instead of elements?
Or should I get all the class names, and loop through to find one that begins with icon_?
EDIT: I want to write a function that gets any class name starting with icon_, and only those class names. Ultimately, I want to get the portion after the underscore, but it’s not necessarily numeric- my plan was to use a regex (these class names are regular.)
EDIT2: The element I’m trying to get the class name from is already selected, I just need the class name from it (not every element in the document with a class=”icon_…..”)
EIDT3: My real problem was that I mixed data and styling. Since I don’t care to support older browsers, I’m using data-id to hold the id of this datum.
<div class="icon icon_23123" data-id="23123"></div>
If you use classes to store data, HTML5 provides a more convenient way to attach data to an element —
data-attributes. For example:Then you can read the attribute directly (the most cross-browser way):
or use the native
datasetproperty object:or use the jQuery’s
data()method for older browsers (IE10-):It is also possible to use the same
data-attribute to attach individual styles to the element via an attribute selector like.icon[data-id="23123"].