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");
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With