How can I set styles to "*" and pseudo-states using JavaScript?

I would like to enable and disable the outlines of all objects on the page, and I do it with the following CSS code:

*, *:before, *:after {
  outline:1px dotted red;
}

      

How do I do this programmatically from JavaScript, where can I enable or disable it?

I think I can do something like this for a specific tag, but not for *:

document.getElementsByTagName("body")[0].style = "outline:1px dotted red";

      

Pseudocode to enable the loop:

document.getElementByTagName("*").setStyle("outline:1px dotted red");
document.getElementByTagName("*:before").setStyle("outline:1px dotted red");
document.getElementByTagName("*:after").setStyle("outline:1px dotted red");

      

Pseudocode to disable the loop:

document.getElementByTagName("*").setStyle("outline:0px dotted red");
document.getElementByTagName("*:before").setStyle("outline:0px dotted red");
document.getElementByTagName("*:after").setStyle("outline:0px dotted red");

      

+3


source to share


3 answers


Usually, you would not want to iterate over all the objects on your page. If we ignore performance issues, this is also a case of potentially overwriting existing styles that you want to keep.

Drawing from Insert CSS stylesheet as string using Javascript



var node;
function changeAllElementsOutline(outlineWidth) {
  if (!node) {  
    node = document.createElement('style');
    document.body.appendChild(node);
  }
  node.innerHTML = '*, *:before, *:after { outline:' + outlineWidth + 'px dotted red; }'
}
      

<div onClick="changeAllElementsOutline(1);">Set outline</div>
<p onClick="changeAllElementsOutline(0);">Remove outline</p>
      

Run codeHide result


+3


source


The best answer is to keep the style loaded, but make it conditional if there is a class on the body. Then you can enable or disable the style by adding / removing the class.

CSS

body.outline-enabled *, 
body.outline-enabled *:before, 
body.outline-enabled *:after {
    outline: 1px solid red;
}

      



JavaScript:

function addOutline() {
    document.getElementsByTagName('body')[0].classList.add('outline-enabled');
}

function removeOutline() {
    document.getElementsByTagName('body')[0].classList.remove('outline-enabled');
}

      

This way you delegate the hard work of styling whatever it needs to the browsers' CSS engine.

+3


source


You can do something like this:

var elements = document.querySelectorAll('*');
for(var i = 0; i < elements.length; i++) {
  elements[i].style.outline = '1px dotted red';
}

      

document.querySelectorAll

returns a NodeList instance (which is like an array), so you can iterate over its elements.

There is NodeList

no way to style its elements.

+1


source







All Articles