To optimize the process, you can delegate this task to the CSS engine of your browser without iterating through all elements. Here's an example:
;(function(exports) {
var style = document.querySelector("head")
.appendChild(document.createElement("style"));
var styleSheet = document.styleSheets[document.styleSheets.length - 1];
styleSheet.insertRule("* {}", 0);
exports.universal = styleSheet.cssRules[0];
}(window));
Now, you have a window.universal
object that allows you to style all elements easily. For instance:
window.universal.style.border = "1px solid red";
No need to dynamically create the <style>
tag every time. You can include it in the HTML structure as well.
You can test it by executing this snippet:
;(function(exports) {
var style = document.querySelector("head")
.appendChild(document.createElement("style"));
var styleSheet = document.styleSheets[document.styleSheets.length - 1];
styleSheet.insertRule("* {}", 0);
exports.universal = styleSheet.cssRules[0];
}(window));
console.log("universal" in window); // true
window.universal.style.border = "1px solid red";
<div>
Hello
<span>World</span>
</div>