使用jquery在body [all elements]中搜索一个类

时间:2014-05-04 00:44:56

标签: javascript jquery html

我需要搜索有show-item-10类的html页面,我必须拆分它 例如,我的html页面中有以下div标签,我想使用类名sell-item-*找到元素

<div class="sell-item-10 item_container">Item 1</div>
<div class="buy-item-2 item_container">Item 2</div>
<div class="sell-item-22 item_container">Item 3</div>
<div class="buy-item-3 item_container">Item 4</div>
<div class="sell-item-20 item_container">Item 5</div>
<div class="sell-item-20 item_container">Item 6</div>

我想只获取我搜索辅助类item_container

的类

2 个答案:

答案 0 :(得分:2)

您可以使用选择器:.item_container[class*="sell-item"]

[attr*=value]

  

表示属性名称为attr的元素,其值至少包含一个字符串“value”作为子字符串。 (mdn)

Example Here

$('.item_container[class*="sell-item"]');

答案 1 :(得分:0)

一种(相对)简单的方法:

// selecting each element with a class attribute, then iterating over that
// collection, using each:
$('[class]').each(function(){

    // caching the classnames in an array (splitting the string using split()):
    var classes = this.className.split(/\s/);

    // iterating over each member of that array:
    for (var i = 0, len = classes.length; i < len; i++){

        // if the current class-name starts with 'sell-item':
        if (classes[i].indexOf('sell-item') === 0) {

            // we set properties of the current element-node over which we're
            // iterating (with 'each()').
            // classes[i] is the full class-name (that started with 'sell-item',
            // classes[i].replace(...) is replacing not-numbers (\D), with empty
            // strings (to reduce that string to just the number components):
            this.sellItemClassName = classes[i];
            this.sellItemNumber = classes[i].replace(/\D/g,'');
        }
    }
}).text(function(i,t){
    // almost irrelevant, just to show how to retrieve the properties we set:
    return t + ' (' + this.sellItemClassName + ', ' + this.sellItemNumber + ')';
});

JS Fiddle demo

参考文献: