JQuery: get class name from multiclass element

I have selected the following item. What is the best way to get the class name icon_23123?

<div class="icon icon_23123"></div>

Is there something like [class ^ = "icon_"] for selecting attributes instead of elements? Or should I get all the class names and scroll to find the one that starts with the _ icon?

EDIT: I want to write a function that gets any class name, starting with the letter "icon_", and only those class names. Ultimately, I want to get the part after the underscore, but it's not necessarily a number — my plan was to use a regular expression (these class names are regular.)

EDIT2: the element that I am trying to get from the class name is already selected, I just need the class name from it (not every element in the document with the symbol class = _..... ").

EIDT3: My real problem was that I was mixing data and style. Since I do not want to support older browsers, I use the data identifier to store the identifier of this database.

<div class="icon icon_23123" data-id="23123"></div>
0
source share
2 answers

If you use classes to store data, HTML5 provides a more convenient way to bind data to an element - data-attributes . For instance:

<div class="icon" data-id="23123"></div>

Then you can read the attribute directly (most cross-browser):

var id = myelement.getAttribute('data-id');

or use your own object dataset:

var id = myelement.dataset.id;

jQuerys data() (IE10 -):

var id = $(myelement).data('id');

data- , .icon[data-id="23123"].

+3

.attr() .each():

$('[class^="icon_"]').each(function () { console.log($(this).attr('class'); });

, , icon_ . .attr. n- , $('[class^=icon_]:eq(n)').attr('class')

( ):

var classes = $(selectedElement).attr('class'),
    iconIndex = classes.indexOf('icon_'),
    iconIndex2 = classes.indexOf(' ', iconIndex),
    theClassName = classes.slice(iconIndex, (iconIndex2 > -1) ? iconIndex2 : undefined)

API: each attr

+1

All Articles