Adding a class to a root element
Well, for purpose of what you are trying to do I would say just CSS could do it.

Using the :focus selector and combining with a span element like this:



input:focus + span:after {
    content: 'Focused!';
}

/* just polishing the looks from here on */
button {
 display: block;
}
span {
  margin: 0 10px;
}
&lt;div id="my-root-element"&gt;
    &lt;input type="text"&gt;&lt;span&gt;&lt;/span&gt;
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/div&gt;




About your JavaScript optimization question two things strikes me:


don't define functions inside loops if you don't need to.
I don't see why to use the setTimeout. Is there any browser mixing up the order of the events?


So a suggestion, without the function declaration inside the loop, using a closure and .toggle() instead of a ternary for add/remove:

const rootElement = document.getElementById('my-root-element');
((rootElement, children) =&gt; {
    const update = () =&gt; {
        rootElement.classList.toggle('focused', children.indexOf(document.activeElement) !== -1);
    };
    children.forEach(el =&gt; {
        ['focus', 'blur'].forEach((eventName) =&gt; {
            el.addEventListener(eventName, update);
        });
    });
})(rootElement, [...rootElement.children]);