Search code examples
javascripthtmlselectors-api

querySelectorAll select children but not grandchildren Vanilla Javascript


This may seem like a duplicate to Selecting <li> child node but not grandchildren with vanilla JavaScript and Selecting children elements but NOT grandchildren, but it is a good bit different.


I have an element in js:

var element = document.getElementBySomething(...);

The element has a lot of children with class layer, some of them children, and some of them grandchildren.

This element is being passed into a function for further use...

In this function, how would you get only the children (not grandchildren) of the element using querySelectorAll

I tried the following:

element.querySelectorAll(" > .layer")

However, this does not work, as it is not a valid css selector.

I know it is possible to do something like: querySelectorAll("#my_id > .layer"), but I already have an element passed into a function, which may not have an id, class, etc. that I can easily identify it with.

How would I go about doing this?

Something like: document.querySelectorAll(element + " > .layer")

Thanks for the help!


Solution

  • You can filter element's children. Working demo.

    // matchSelector
    var matches = (function(p){
      return p.matches 
             || p.webkitMatchesSelector
             || p.mozMatchesSelector
             || p.msMatchesSelector 
    }(Element.prototype))
    
    var layers = [].filter.call(element.children, function(el) { 
      return matches.call(el, '.layer')
    });