Skip to content Skip to sidebar Skip to footer

How To Set The Universal Css Selector With Javascript?

I often use the CSS universal selector to reset the dimensions in my HTML document: * { border: 0; margin: 0; padding: 0; } Can this be done with JavaScript too? Fo

Solution 1:

getElementsByTagName("*") will return all elements from DOM. Then you may set styles for each element in the collection:

var allElements = document.getElementsByTagName("*");
for (var i = 0, len = allElements.length; i < len; i++) {
    var element = allElements[i];
    // element.style.border = ...
}

Solution 2:

You don't need to iterate all the elements. You can demand this operation to the CSS engine of your browser. Something like that:

;(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));

From now, you have a window.universal object that you can use to style all the elements. For instance:

window.universal.style.border = "1px solid red";

Of course you don't need to create at runtime the <style> tag. You can always have that in plain HTML too.

You can test it running 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"inwindow); // truewindow.universal.style.border = "1px solid red";
<div>
  Hello
  <span>World</span></div>

Solution 3:

In raw javascript you can do this:

document.getElementsByTagName('*')

but I wouldn't recommend adding css to all elements using js.

Solution 4:

Thanks VisioN for the solution! I just remembered that you can do the same with the new JavaScript Query Selector API:

var allElements = document.querySelectorAll('*');

for (var i = 0; i < allElements.length; i++) {
  var element = allElements[i];        
  element.style.border = '0px';
  element.style.margin = '0px';
  element.style.padding = '0px';
}

Post a Comment for "How To Set The Universal Css Selector With Javascript?"