jQuery - 提取以'前缀'开头的类名

时间:2013-06-28 14:56:23

标签: javascript jquery

我的项目包含以下课程:

<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>

我想知道是否有一种简单的方法:

  1. 仅抓取所有带有some-class-前缀的课程。
  2. 从每个元素中删除它们。
  3. 在变量中有他们的名字(不是相应的DOM元素)吗?
  4. 我可以轻松地用jQuery( "div[class^='some-class-'], div[class*=' some-class-']" )选择这样的元素,但是如何用变量的最短和最可读的代码提取它的类名(可以是某个全局对象)?

4 个答案:

答案 0 :(得分:13)

喜欢这个吗?

var arrClasses = [];
$("div[class*='some-class-']").removeClass(function () { // Select the element divs which has class that starts with some-class-
    var className = this.className.match(/some-class-\d+/); //get a match to match the pattern some-class-somenumber and extract that classname
    if (className) {
        arrClasses.push(className[0]); //if it is the one then push it to array
        return className[0]; //return it for removal
    }
});
console.log(arrClasses);

<强> Fiddle

.removeClass() 接受一个回调函数来执行某些操作并返回要删除的className,如果没有要删除的内容则不返回任何内容。

答案 1 :(得分:4)

您可以遍历所有元素,使用正则表达式提取类名,并将它们存储在数组中:

var classNames = [];
$('div[class*="some-class-"]').each(function(i, el){
    var name = (el.className.match(/(^|\s)(some\-class\-[^\s]*)/) || [,,''])[2];
    if(name){
        classNames.push(name);
        $(el).removeClass(name);
    }
});
console.log(classNames);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="class-x some-class-1 other-class"></div>
<div class="some-class-45 class-y"></div>
<div class="some-class-123 something-else"></div>

答案 2 :(得分:1)

您可以迭代每个找到的节点并遍历类以查找匹配项;如果找到,请删除该类并将其记录下来:

var found = [];

$('div[class*="some-class-"]').each(function() {
  var classes = this.className.split(/\s+/),
  $this = $(this);

  $.each(classes, function(i, name) {
      if (name.indexOf('some-class-') === 0) {
          $this.removeClass(name);
          found.push(name);
      }
  });
});

请注意,像div[class*="some-class-"]这样的选择器非常昂贵,因为无论如何都需要执行额外的处理,所以迭代所有div标记并处理它们会更容易:

var elements = document.getElementsByTagName('div'),
found = [];

$.each(elements, function(i, element) {
    var classes = element.className.split(/\s+/);

    $.each(classes, function(i, name) {
        if (name.indexOf('some-class-') === 0) {
            $(element).removeClass(name);
            found.push(name);
        }
    });
});

现代浏览器公开Element.classList,您可以使用它来操作类名称和Array.forEach进行迭代:

var found = [];

[].forEach.call(document.getElementsByTagName('div'), function(element) {
    (function(names, i) {
        while (i < names.length) {
            var name = names[i];
            if (name.indexOf('some-class-') === 0) {
                names.remove(name);
                found.push(name);
            } else {
                ++i;
            }
        }
    }(element.classList, 0));
});

答案 3 :(得分:-1)

简单方法

您可以创建自己的过滤器:

$.fn.hasClassStartsWith = function(className) {
    return this.filter('[class^=\''+className+'\'], [class*=\''+className+'\']');
}

var divs = $('div').hasClassStartsWith("some-class-");
console.log(divs.get());

See fiddle