Find dynamic classname of element with jQuery

丶灬走出姿态 提交于 2019-12-21 06:09:12

问题


I'm having a unknown number of elements like so:

<div class="item item-1"></div>
<div class="item item-2"></div>
<div class="item item-3"></div>

What I want to do, is check if each item has a classname starting with "item-". If true, then extract the id. Something like this:

$("container").each(function
    if ($(this).hasClassNameStartingWith("item-"))
        console.debug(theId);
);

How is this possible?

Thanks in advance!


回答1:


Use the contains selector on the class attribute:

$('container[class*=" item-"]').each( function() {
    var classID = null;
    var classes = $(this).attr('class').split( ' ' );
    for (var i = 0, len < classes.length; i < len; ++i) {
        var class = classes[i];
        if (class.match( /^item-/ )) {
            classID = class.replace("item-",'');
            break;
        }
    }
    if (classID) {
        ... do something ...
    }
});

Note the use of quotes to include the space, given your sample mark up. You could also omit the space if the "item-N" class could appear at the beginning of the list and you were sure that there weren't any classes that would accidentally match that string.

Updated example to show how to extract identifier portion of class name.




回答2:


You can perform a regular expression match on the child elements' class attribute:

var itemIDRe = /(?:^|[ \t\n\r\f\u200b]+)item-([^ \t\n\r\f\u200b]+)/;

$('#container').children().each(function() {
  var match = itemIDRe.exec($(this).attr('class'));
  var itemID = match ? match[1] : null;

  // Do something with itemID.
});

The regular expression is based on the HTML 4 definition for the class attribute and white space.



来源:https://stackoverflow.com/questions/1669066/find-dynamic-classname-of-element-with-jquery

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