jQuery: Get class name from multiclass element

一世执手 提交于 2019-12-13 03:36:22

问题


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>

回答1:


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

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

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

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

or use the native dataset property object:

var id = myelement.dataset.id;

or use the jQuery’s data() method for older browsers (IE10-):

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

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"].




回答2:


use .attr() combined with .each():

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

This passes all elements which have a class name that starts with icon_ and pass it to the each function. You can then access the attribute of the element using .attr. If you only need to access the nth element, you could use $('[class^=icon_]:eq(n)').attr('class')

edit (answer to comment):

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

API documentation: each attr



来源:https://stackoverflow.com/questions/9550957/jquery-get-class-name-from-multiclass-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!