Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the styles on "*" and pseudo states with JavaScript? [closed]

I'd like to enable and disable outlines on all objects on a page and I'm doing that with the following CSS code:

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

How would I do that programmatically with JavaScript where I can 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";

Pseudo code to enable outline:

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

Pseudo code to disable outline:

document.getElementByTagName("*").setStyle("outline:0px dotted red");
document.getElementByTagName("*:before").setStyle("outline:0px dotted red");
document.getElementByTagName("*:after").setStyle("outline:0px dotted red");
like image 665
1.21 gigawatts Avatar asked Dec 05 '25 17:12

1.21 gigawatts


1 Answers

You generally would NOT want to loop through all objects on your page. If we ignore performance issues, there's also the case of actually potentially overwriting existing styles that you want to keep.

Drawing from Inject 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>
like image 69
Jan Avatar answered Dec 08 '25 06:12

Jan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!