Search code examples
javascriptchildrenselectors-api

querySelectorAll root elements without using :scope


Let's assume we have this HTML structure:

<div id='test-div'>
    <div class='random-class-1'>
        <div class='useless-element-1'>
        </div>
        <div class='useless-element-2'>
        </div>
        <p>Just a paragraph, and useless</p>
    </div>
    <div class='random-class-2'>
        <div class='useless-element-3'>
        </div>
        <div class='useless-element-4'>
        </div>
        <div class='useless-element-5'>
        </div>
    </div>
</div>

I need to select all children "DIV elements" (not grandchildren) inside the first DIV (in this example with id='test-div'), not from document but from element (div) itself.

So, I don't want to use the "query" below because I already have selected the element DIV [object HTMLDivElement]:

// I don't want to use this query
var children = document.querySelectorAll("div > div");

Just an example to achieve this (https://jsfiddle.net/t4gxt65k/):

// I already have selected DIV element 
var el = document.getElementById("test-div")
// OR var el = document.querySelectorAll("#test-div");

var children = el.querySelectorAll(":scope > div");

But because of browser incompatibility I don't want to use ":scope"

The real question is:

How can I get the children (only DIV elements) of [object HTMLDivElement] using pure JavaScript?


Solution

  • To get direct children of an element use a combination of parentNode.children or parentNode.childNodes, and Array.prototype.reduce like this:

    var children = Array.prototype.reduce.call(el.children, function(acc, e) {
        if(e.tagName == "DIV")
            acc.push(e);
        return acc;
    }, []);