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

Search for a class in body [all elements] using jquery

本文关键字:搜索 一个 jquery body elements all 使用      更新时间:2023-09-26

我需要搜索有像show-item-10类的html页面,我必须分割它例如,我有以下div标签在我的html页面,我想找到元素使用类名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

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

Where [attr*=value]

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

例子

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

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

// 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.

引用:

  • JavaScript:
      JavaScript正则表达式
  • String.replace() .
  • String.split() .
  • jQuery:
    • each() .
    • text() .