Search code examples
javascripthtmlcssstylesdarkmode

.style.color don't change the color of an element in JavaScript


I would like to add Dark Mode to my site, so I created an HTML file with the css (in "white mode") and then i added a button (with the attribute onclick="enableDarkMode()") and defined the function like this:

function enableDarkMode() {
    if (document.body.style === "background-color: black;") {
        // disable dark mode
    } else {
        document.body.style = "background-color: black;"
        Array.from(document.getElementsByTagName("a")).forEach(e => {
            e.style.color = "white"
        });
        document.getElementsByTagName("h1")[0].style.color = "white"
        document.getElementsByTagName("img")[0].style = "box-shadow: 0px 4px 6px 2px #404040;"
    }
}

when i run everything and i click the Enable Dark Mode it just changes the background and it doesn't turn the text color in white even if they have the attribute style = "color: white;"

here's the full code: https://codepen.io/anonhexo/pen/WNGmevq


Solution

  • Your problem is that you are overriding the color of this <a> by using !important in your css.

    If you inspect the element, and click on computed, you can see where the color is coming from. If you toggle dark mode you can see that white is there, but it has a line through it. The one that doesn't have the line through it is the one that is being used.

    It seems to work fine if you remove !important from the css (both instances)

    As a general rule of thumb, try not to use important as much as you can as you can get problems like this. In some situations it is neccessary, but not many.