1

I'm making a script to invert color of a HTML page. So it is easier to look at at night. I'm using filter: invert(100%) to do it.

Here is the script:

document.body.style.filter = "invert(100%)";
Object.values(document.body.getElementsByTagName("*")).forEach(e => {
    e.style.filter = "invert(100%)"
});

However it didn't really work.

Inverted

The Stack Overflow logo on the header is gone, as well as the buttons. What did I do wrong, and is there a better method than this?

Thanks in advance.

Gruber
  • 2,196
  • 5
  • 28
  • 50
Green Ball
  • 64
  • 9
  • Does this answer your question? [JavaScript: Invert color on all elements of a page](https://stackoverflow.com/questions/4766201/javascript-invert-color-on-all-elements-of-a-page) – ggorlen Dec 23 '20 at 19:52

1 Answers1

2

Your solution:

document.body.style.filter = "invert(100%)";
Object.values(document.body.getElementsByTagName("*")).forEach(e => {
    e.style.filter = "invert(100%)"
});

didn't really work because you're inverting colours from parent elements and their children. Inverting twice causes the element to have the original colour. Therefore, you only need to invert the colour of the parent(s) (in this case, the html, which is the root of everything):

document.querySelector('html').style.filter = 'invert(100%)'

And every colour will be inverted. Note that if you try to use this on a colourless element, nothing will change, i.e. if you try this script on this page, you will notice that the div on the left side of this page with the id left-sidebar will not change in colour. This is due to the sidebar not having any colour (the middle section and right sidebar is inverted because they're inside the div#content which has white background colour).

However, if you add background (e.g. white) to the left side bar, it will also invert its colour.

Gruber
  • 2,196
  • 5
  • 28
  • 50
Richard
  • 7,037
  • 2
  • 23
  • 76