如何选择类名以多于一次开头的元素?

时间:2015-02-03 09:00:54

标签: javascript jquery

在应用程序中,我在元素中添加了一个类名userNoteuserNotenumbers作为帖子固定,如下所示:userNote1

用户可以多次选择相同的元素。所以,我想知道该元素具有多个class名称,这些名称以相同的模式开头,对我来说是“userNote'。

我可以像这样过滤:

$('body').find('*').filter(function () {
    return this.className.match(/\buserNote/);
//it returns the value, but i don't know how many class name it has!
    });

但我要求elements只有多个class名称具有相同的统计名称。

Live Demo

3 个答案:

答案 0 :(得分:2)

最简单的方法是在空格上拆分className,然后循环结果,查找从字符串开始在数组中获得多个条目的元素。

// Start out with a set of elements that have "userNote" anywhere
// in the class, then filter based on the more detailed criteria
var matches = $('[class*=userNote]').filter(function () {
    return this.className.split(' ').reduce(function(p, c) {
        return c.substring(0, 8) === "userNote" ? p + 1 : p;
    }, 0) > 1;
});

现在,matches包含一组元素,这些元素包含多个以userNote开头的类。

(使用ES5功能Array#reduce,但可以为旧版浏览器填充,或者您只需使用简单的for循环。)

示例:

// Start out with a set of elements that have "userNote" anywhere
// in the class, then filter based on the more detailed criteria
var matches = $('[class*=userNote]').filter(function () {
  return this.className.split(' ').reduce(function(p, c) {
    return c.substring(0, 8) === "userNote" ? p + 1 : p;
  }, 0) > 1;
});

// Show results
$("<p>Text of matching elements:<br>" + matches.map(function() {
  return $(this).text();
}).get().join("<br>") + "</p>").appendTo(document.body);
<div class="userNote">one</div>
<div class="userNote userNote2">two</div>
<div class="userNote userNote2 userNote3">three</div>
<div class="foo">none</div>
<div class="foo userNote userNote2 userNote3 userNote4 bar">four and other classes</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

答案 1 :(得分:-1)

尝试以下选择器

$("p[class*=userNote]").css('color', 'blue');

参考:http://api.jquery.com/attribute-contains-selector/

答案 2 :(得分:-1)

试试这个, 它将使用 userNote 选择所有元素并具有突出显示类

$('body').find('[class*=userNote].highlight').length

我希望这正是你所需要的