Categories
JavaScript Answers

How to Invert Color on All Elements of a Page with JavaScript?

Spread the love

Sometimes, we want to invert color on all elements of a page with JavaScript.

In this article, we’ll look at how to invert color on all elements of a page with JavaScript.

Invert Color on All Elements of a Page with JavaScript

To invert color on all elements of a page with JavaScript, we just set use the invert(100%) value with CSS.

For instance, if we have:

<div style='background-color: white'>
  hello
</div>

Then we can invert all the colors by writing:

const css = `html {
  -webkit-filter: invert(100%);
  -moz-filter: invert(100%);
  -o-filter: invert(100%);
  -ms-filter: invert(100%);
}`
const head = document.head
const style = document.createElement('style')
style.type = 'text/css';
if (style.styleSheet) {
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}
head.appendChild(style);

We create the css string to set the filter property to invert(100%) on the html element.

Then we get the head element with document.head .

Then we create the style element with document.createElement .

We set the type attribute of style by assigning a value to style.type .

And then we apply the styles from the css string with:

if (style.styleSheet) {
  style.styleSheet.cssText = css;
} else {
  style.appendChild(document.createTextNode(css));
}
head.appendChild(style);

to set the content of the style element and append it to the head with head.appendChild .

Conclusion

To invert color on all elements of a page with JavaScript, we just set use the invert(100%) value with CSS.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *