Is it possible to use querySelectorAll for an array of elements?

Say I have an array of DOM elements based on any selector

var elems = document.querySelectorAll(selector);

I do not know what is included in elems, but suppose thatelems.length > 0

I would like to use querySelectorAll (or some equivalent function) on elemsto find all the elements that match the optional selector.

// example: find all buttons with class `foo` within `elems` array
var buttons = elems.querySelectorAll("button.foo");

This does not work (for obvious reasons), but I'm not sure how to do it otherwise :(


Here's a wrapper that I created to work with the accepted answer from @Tibos

// Element.matches wrapper
(function(e){
  if (typeof e.matches !== "function") {
    e.matches = e.webkitMatchesSelector ||
                e.mozMatchesSelector    ||
                e.msMatchesSelector     ||
                e.oMatchesSelector      ||
                e.matchesSelector;
  }
})(Element.prototype);
+4
source share
4 answers

You can use the method Element#matchesto filter the source list:

var elems = document.querySelectorAll(selector);
var buttons = Array.prototype.filter.call(elems, function(elem){ 
  return elem.matches('button');
});

, , , . (, !)

- , document.querySelectorAll . , , . .

+5

correct!!

0

, matches .

function getElementsFromParents(parentSelector, childSelector) {
    var elems = document.body.querySelectorAll(parentSelector);
    return Array.prototype.reduce.call(elems, function matcher(arr, el) {
        var matches = el.querySelectorAll(childSelector);
        if (matches.length) Array.prototype.forEach.call(matches, function pusher(item) {
            arr.push(item);
        });
        return arr;
    }, []);
}
0

querySelectorAll NodeList, , .

  var lines = Array.prototype.slice.call(document.querySelectorAll(selector));
  var paths = lines.map(function(elem){ 
    return elem.querySelector('button');
  });
0

Source: https://habr.com/ru/post/1527567/


All Articles