在JavaScript中使用RegExp查找所有匹配的选择器

时间:2014-10-18 23:31:48

标签: javascript

在JavaScript中是否可以使用RegExp查找所有选择器?

例如,如何查找所有选择器element1element2,... element21341234

document.querySelectorAll('.element + [regexp]')

3 个答案:

答案 0 :(得分:7)

根据所提供的信息,我建议:

// using Array.prototype.filter, to filter the elements returned by
// 'document.querySelectorAll()'
var elementPrefixed = [].filter.call(document.querySelectorAll('[class*=element]'), function(el) {
  // '\b' is a word-boundary,
  // 'element' is the literal string
  // \d+ is a string of numeric characters, of length one or more:
  return (/\belement\d+\b/).test(el.className);
});

// iterates over the found elements, to show those elements that were found:
[].forEach.call(elementPrefixed, function(el) {
  el.style.color = '#f90';
});
div {
  height: 2em;
  border: 1px solid #000;
  margin: 0 auto 0.5em auto;
  width: 50%;
}
div[class]::before {
  content: attr(class);
}
<div class="element1"></div>
<div class="element2"></div>
<div class="element3"></div>
<div class="element4"></div>
<div class="elementOther"></div>
<div class="element"></div>
<div class="2element"></div>
<div class="3element1"></div>
<div class="4element15"></div>

或者,也可以扩展Document原型以提供document.getElementsByRegex()方法:

// adding a method to the Document.prototype:
Document.prototype.getElementsByRegex = function (attr, reg) {
  // attr: String, an attribute of the element you wish to search by,
  // reg: a RegExp literal which should perform the search.

  // here we find all elements in the document with the specific attribute:
  var superSet = document.querySelectorAll('[' + attr + ']');

  // if there are no elements with that attribute, we return null:
  if (!superSet.length) {
    return null;
  }
  else {
    // otherwise we return a filtered array, of those elements
    // which have an attribute matching the regular expression:
    return [].filter.call(superSet, function (el) {
      // we're using 'el.getAttribute(attr),' rather than el[attr],
      // because searching by class would require el[className], and 'for'
      // would require el[HTMLFor]; getAttribute irons out those kinks:
      return reg.test(el.getAttribute(attr));

      // Note that this method returns an Array, not a NodeList (live or otherwise)
      // unlike document.getElementsByClassName() for example

    });
  }
};

// adding a method to the Document.prototype:
Document.prototype.getElementsByRegex = function (attr, reg) {
  // attr: String, an attribute of the element you wish to search by,
  // reg: a RegExp literal which should perform the search.

  // here we find all elements in the document with the specific attribute:
  var superSet = document.querySelectorAll('[' + attr + ']');

  // if there are no elements with that attribute, we return null:
  if (!superSet.length) {
    return null;
  }
  else {
    // otherwise we return a filtered array, of those elements
    // which have an attribute matching the regular expression:
    return [].filter.call(superSet, function (el) {
      // we're using 'el.getAttribute(attr),' rather than el[attr],
      // because searching by class would require el[className], and 'for'
      // would require el[HTMLFor]; getAttribute irons out those kinks:
      return reg.test(el.getAttribute(attr));

      // Note that this method returns an Array, not a NodeList (live or otherwise)
      // unlike document.getElementsByClassName() for example

    });
  }
};

console.log(document.getElementsByRegex('id', /\belement\d+\b/));
div {
  height: 2em;
  border: 1px solid #000;
  margin: 0 auto 0.5em auto;
  width: 50%;
}
div[class]::before {
  content: attr(class);
}
<div class="element1"></div>
<div class="element2"></div>
<div class="element3"></div>
<div class="element4"></div>
<div class="elementOther"></div>
<div class="element"></div>
<div class="2element"></div>
<div class="3element1"></div>
<div class="4element15"></div>

参考文献:

答案 1 :(得分:0)

querySelectorAll(selector)将一个字符串作为其selector参数,因此您无法将其传递给正则表达式。如果您需要正则表达式,请参阅David Thomas's answer

但是,根据您的使用情况,您可能不需要正则表达式,因为字符串参数可以是以逗号分隔的选择器列表。

所以,如果你真正想要的只是.element1.element2.element3,你可以将它们全部作为单个字符串传递,每个字符串用逗号分隔:

var elements = document.querySelectorAll('.element1,.element2,.element3');

答案 2 :(得分:0)

如果你的元素&#39;课程是.element1.element2.element3,等等,您可以尝试这样的事情:

// Create an array from 1 to 5
var x = Array.apply(null, Array(5)).map(function (_, i) {return i + 1;});
var elems = [];

for (i = 0; i < x.length; i++) {
  var element = document.querySelectorAll('.element' + x[i]);
  elems.push(element);
}