Adding a class to a root element I have written some ES2015 JavaScript that adds a class to a root element when one of it's immediate children is focused.

Here is the markup for the code to be run on:

&lt;div id="my-root-element"&gt;
    &lt;input type="text"&gt;
    &lt;button type="submit&gt;
&lt;/div&gt;


And the JS itself:

const rootElement = document.getElementById('my-root-element');

[...rootElement.children].forEach((element, _, children) =&gt; {
  const update = () =&gt; {
    const focused = children.indexOf(document.activeElement) !== -1;

    rootElement.classList[focused ? 'add' : 'remove']('focused');
  };

  [ 'focus', 'blur' ].forEach((eventName) =&gt; {
    element.addEventListener(eventName, () =&gt; setTimeout(update, 0));
  });
});


Are there any ways to "simplify" this code or generally make it smaller? I know it's short as it is currently but I understand that ES2015 has a lot of features that can help in writing short, concise code.

Here is an actual example of the code being used (focusing either the button or the text field should make the word "Focused!" appear):



const rootElement = document.getElementById('my-root-element');

[...rootElement.children].forEach((element, _, children) =&gt; {
  const update = () =&gt; {
    const focused = children.indexOf(document.activeElement) !== -1;

    rootElement.classList[focused ? 'add' : 'remove']('focused');
  };

  [ 'focus', 'blur' ].forEach((eventName) =&gt; {
    element.addEventListener(eventName, () =&gt; setTimeout(update, 0));
  });
});
.focused:after {
  content: 'Focused!';
}
&lt;div id="my-root-element"&gt;
    &lt;input type="text"&gt;
    &lt;button type="submit"&gt;Submit&lt;/button&gt;
&lt;/div&gt;
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]);