admin管理员组

文章数量:1336632

Is it possible in JavaScript to find all selectors using RegExp?

For example, how can I find all selectors element1, element2, ... element21341234?

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

Is it possible in JavaScript to find all selectors using RegExp?

For example, how can I find all selectors element1, element2, ... element21341234?

document.querySelectorAll('.element + [regexp]')
Share Improve this question asked Oct 18, 2014 at 23:31 barbarabarbara 3,2018 gold badges32 silver badges58 bronze badges 4
  • What are you trying to achieve with the regex, that a regular selector couldn't achieve? – David Thomas Commented Oct 18, 2014 at 23:43
  • I want to retrieve an array of elements. But I don't know their numbers. I know only first part of class - element. – barbara Commented Oct 18, 2014 at 23:49
  • Could you give us a clue as to what you're trying to match with this regular expression? A sample of the relevant HTML would be very useful (and, frankly, mandatory in a question involving CSS). – David Thomas Commented Oct 18, 2014 at 23:50
  • Ok. I know that class on elem is .element[some number]. but numbers is unknown for me. I need to find when in DOM. – barbara Commented Oct 18, 2014 at 23:52
Add a ment  | 

3 Answers 3

Reset to default 8

Given the information provided, I'd suggest:

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

Alternatively, it's also possible to extend the Document prototype to offer a document.getElementsByRegex() method:

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

References:

  • CSS:
    • Attribute-presence and value selectors.
    • Substring-matching ([attribute*=value]) attribute selectors.
  • JavaScript:
    • Array.prototype.filter().
    • Array.prototype.forEach().
    • Element.getAttribute().
    • Function.prototype.call().
    • JavaScript Regular Expressions.
    • RegExp.test().

If your elements' classes are .element1, .element2, .element3, and so on, you can try something like this:

// 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);
}

querySelectorAll(selector) takes a string as its selector argument, so you there's no way to just pass it a regular expression. If you need regular expressions, see David Thomas's answer.

However, you might not need a regular expression depending on your use case, as the string argument can be a ma-separated list of selectors.

So, if all you really want is .element1, .element2, and .element3, you can just pass them all in as a single string with each one separated by mas:

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

本文标签: Find all matched selectors with RegExp in JavaScriptStack Overflow