How to set the universal CSS selector with JavaScr

2019-01-28 11:16发布

问题:

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?

For normal HTML elements there is the style property. But how to speak to the universal selector?

回答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 = ...
}


回答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.



回答3:

In raw javascript you can do this:

document.getElementsByTagName('*')

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



回答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';
}