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

3

在JavaScript中,使用RegExp是否可能找到所有的选择器?

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

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

你使用正则表达式想要实现什么,而普通选择器无法实现的呢? - David Thomas
我想检索一个元素数组,但我不知道它们的数量。我只知道类的第一部分 - element - barbara
你能否给我们一些线索,告诉我们你试图用这个正则表达式匹配什么?提供相关HTML的样本将非常有用(而且,在涉及CSS的问题中,坦率地说是必需的)。 - David Thomas
好的。我知道在元素上的类是.element[some number],但是这个数字对我来说是未知的。我需要找到它在DOM中的位置。 - barbara
3个回答

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

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

参考资料:


elementOther、2element、3element1、4element15 都不是有效的元素。 - barbara
没有更改CSS的可能性。 - barbara
您不必更改CSS,CSS仅用于显示函数选择的内容,以及特定元素;这只是一个演示。如果您展示了自己的HTML(正如我所请求的),那么我会与之配合。而且,是的:CSS名称是有效的(在HTML 5中),只是在CSS中更难选择它们(需要转义)。 - David Thomas
我很高兴能够帮助。 - David Thomas

0
如果您的元素类是.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);
}

我需要获取一个元素数组。 - barbara
但是我不知道总数(可能是5个或其他数字)。我甚至可以有元素 element1element45element8546。因此,数量是未知的。 - barbara
我不知道。可能是五个或一百个。实际上问题是如何找到它们全部。我需要用 JavaScript 找到它们。 - barbara
它们都是 div 元素吗? - Weafs.py
不,它们可以是任何类型的元素。 - barbara
它们都是class,对吗?我的意思是没有id - Weafs.py

0

querySelectorAll(selector) 接受一个字符串作为其 selector 参数,因此您无法直接传递一个正则表达式。如果您需要正则表达式,请参见 David Thomas 的答案

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

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

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

但是我不知道元素的数字(1,2,3)。我的意思是,也许我可以使用正则表达式。 - barbara

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接