It is not possible to modify the color of an element using the .style.color property in JavaScript

I've been working on incorporating a Dark Mode feature into my website. I started by creating an HTML file with the CSS set in "white mode." Then, I added a button with the attribute onclick="enableDarkMode()" and defined the function as follows:

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;";
    }
}

After running the code and clicking on Enable Dark Mode, I noticed that only the background color changed and the text color remained unchanged despite having the style attribute set to "color: white."

If you want to take a look at the full code, here's the link: https://codepen.io/anonhexo/pen/WNGmevq

Answer №1

The issue lies in the fact that you are overriding the color of the <a> element by applying !important in your CSS.

If you inspect the element and navigate to the computed styles, you will be able to identify where the color is originating from. By switching to dark mode, you can observe that white is present but crossed out. The one without the strike-through is the one taking effect.

To resolve this issue, consider removing the !important declaration from your CSS (in both occurrences).

It's advisable to minimize the use of !important as much as possible to avoid complications like this. While there are situations where it may be necessary, they are few and far between.

Answer №2

    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.setProperty("color", "white", "important");

            });
            document.getElementsByTagName("h1")[0].style.color = "white !important"
            document.getElementsByTagName("img")[0].style = "box-shadow: 0px 4px 6px 2px #404040;"
        }
    }
.dark-mode {
            position: absolute;
            top: 0;
            right: 0;
            font-size: 13px;
        }

        .about {
            margin-bottom: 80px;
        }

        .text-center {
            text-align: center;
        }

        .profile-pic {
            box-shadow: 0px 4px 6px 2px lightgrey;
            border-radius: 50%;
        }

        img {
            vertical-align: middle;
        }

        img {
            border: 0;
        }

        h1,
        h2,
        h3,
        h4,
        h5,
        a {
            color: #4A4E69 !important;
            font-weight: 300;
            font-family: 'Open Sans', sans-serif;
        }

        a:hover {
            transition-duration: 0.5s;
            color: #d1d3e2 !important;
        }

        a:not(:hover) {
            transition-duration: 0.5s;
            color: #4A4E69 !important;
        }

        .h1,
        h1 {
            font-size: 36px;
        }
<html>

<head>
    <title>AnonHexo</title>
    <a class="dark-mode" style="text-decoration:none" onclick="enableDarkMode()">Enable Dark Mode</a>
</head>

<body>
    <section class="about">
        <div class="text-center" style="margin-top:100px"> <img
                src="https://avatars1.githubusercontent.com/u/61375258?v=4" width="200" class="profile-pic">
            <h1>AnonHexo, Italy</h1>
            <div class="socialLinks">
                <a href="https://www.github.com/AnonHexo" style="text-decoration:none" target="_blank">GitHub</a>,
                <a href="https://www.stackoverflow.com/users/13221104/anonhexo?" style="text-decoration:none"
                    target="_blank">Stack Overflow</a>,
                <a href="https://codepen.io/anonhexo" style="text-decoration:none" target="_blank">Codepen</a>,
                <br>
                <a href="https://www.youtube.com/channel/UCnnqMGII7LHvvn1LUiU55eg" style="text-decoration:none"
                    target="_blank">YouTube</a>,
                <a href="https://www.instagram.com/jacky.trave" style="text-decoration:none"
                    target="_blank">Instagram</a>,
                <a href="https://www.reddit.com/u/AxonHexo" style="text-decoration:none" target="_blank">Reddit</a>,
                <a href="https://www.twitch.tv/AnonHexo" style="text-decoration:none" target="_blank">Twitch</a>
  
            </div>
            <!-- <h5>Young 12 y/o back-end developer.</h5>
            <div class="text-center" style="margin:20px"> <a href="mailto:" class="" target="_blank"> </a> </div> -->
        </div>
    </section>
  <button onclick="enableDarkMode()">
    enable dark mode
  </button>
</body>
</html>

Your CSS rules for the a elements override the new command you give.

Your CSS contains:

a:not(:hover) {
    transition-duration: 0.5s;
    color: #4A4E69 !important;
}

If you want all the a elements to be white, you should do:

e.style.setProperty("color", "white", "important");

Answer №3

The color of the <code>h1 tag has been set to #4A4E69 !important;. To override this, make sure to include !important.

Check out the documentation on setProperty()

Use the following code snippet: 
document.getElementsByTagName("h1")[0].style.setProperty("color", "white", "important")

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is the entire web page generated on the server with each request using getServerSideProps()?

As I understand it, getServerSideProps will dynamically generate the complete page on every request, rather than pre-building it. But does getServerSideProps always generate the entire page upon each server request, or only when the data in the database ha ...

Utilize javascript/jquery for transforming HTML table data to JSON

Whenever I click the "+" button, my table rows are dynamically generated. After populating the fields and clicking the submit button next to "+", the JSON data is displayed in the console, as shown in the image below. While generating the JSON data, I aim ...

What is the best way to utilize the node.js module passport-google?

I'm currently working on a node.js web application that prompts users to sign in using their Gmail account. While following instructions provided at this website, I modified the URL from www.example.com to localhost and launched the application. Howev ...

Working with both Javascript and jQuery code within a single HTML file

I recently created a website and on one of the pages, I added some jQuery elements like a start button and progress bar. However, when I tried to implement a JavaScript timer on the same page by adding the script into the header, the jQuery elements stoppe ...

Grid Alignment Centered - Inner Grid aligned to the left - Zero Javascript or Media Queries Allowed

[UPDATE] Looking for a solution that doesn't involve javascript or media queries as the user should be able to change the container size. [/UPDATE] In need of creating a grid layout for items. The container's width is flexible. The grid must ...

Sending information from JavaScript to Pug templateorTransferring

I'm currently experimenting with Node.js and MongoDB within an Express framework. My current goal is to achieve the following: Establish a connection to MongoDB and retrieve a document from a specific collection (which I have successfully done). Pr ...

Displaying events in the all-day section can be achieved by setting the defaultView of fullCalendar.js to 'agendaDay'

Trying to use fullCalendar.js with defaultView set to agendaDay, and pulling events from mysql as JSON. However, I'm encountering an ERROR where it displays the events in the 'all-Day' section. Here are some of the solutions I attempted: e ...

Calculate the sum of the elements within an array that possess a distinct attribute

I need to calculate the sum of certain elements in an array. For example, let's consider this array: var sampleArray = [ {"id": 1, "value": 50, "active": true}, {"id": 2, "value": 70, "active": false}, ...

The image refuses to align to the left side below a floated paragraph

Hey there, I'm working on some CSS and I've run into an issue. I have two paragraphs and I want to place a picture below the paragraph on the left side. The left paragraph is longer than the one on the right, which seems to be causing the picture ...

Tips for swapping out a specific string in an HTML webpage with a different string using JavaScript

For my HTML website, I am trying to replace one string with another using JavaScript. Specifically, within the nodeList "AuthorList," there is a string called "Test String" that needs to be changed to "new test." I have attempted various modifications of ...

Is there a way to programmatically emulate Firebug's inspect element feature using JavaScript?

Is there a straightforward method in JavaScript or any popular libraries like YUI or jQuery to allow users to interact with elements on a website, similar to the functionality of Firebug for developers? ...

Is 100% truly the same as 100%?

When positioning two divs side by side with widths set in percentages, a total of 100% is often too wide and results in the divs not sitting next to each other as intended. Reducing the total width to 99% can create an uncomfortably large gap between the ...

Ways to extract a variable from an HTML source using JavaScript and Ajax queries

I'm currently working with Zend Framework 2 and I have a question regarding accessing data defined in HTML within my JavaScript code. Here is the HTML snippet: <tr class="MyClass" data-MyData="<?php echo json_encode($array);?>"> And her ...

Commitment within a forEach iteration

While working with a foreach loop, I am facing some challenges. Here is the scenario: I have multiple elements stored in an object array. For each object, I need to execute two queries. After completing the queries for one object, I move on to the next and ...

Tips on submitting JSON data to a server

I need the data to be structured like this {"email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7f0c3f18121e1613511c1012">[email protected]</a>","password":"1"} but it is currently appearing like this { & ...

Modifying Regular Expression to eliminate trailing decimal points and zeroes when there is no fractional value present

Currently, I am in the process of learning Regex and experimenting with it. One thing I'm working on is creating a function that parses a float number while limiting the number of decimal places. My goal is to only allow a maximum of two decimal point ...

The text rests on a slanted div with a captivating background image

How can I place text over a skewed div with a background image? Despite using the ::before pseudo element, the text is appearing behind the image. Here's an example of what I'm attempting to achieve: Html <div class="diag-right">Text Here ...

When using server-side rendering in React with AJAX, an error may occur if trying to call setState

In order to display data to the user, I rely on the response from the AJAX request as I store all necessary information in the database. My component GenericPage.jsx: export default class GenericPage extends React.Component { componentWillMount() { ...

Turn off the Antd Datepicker tooltip

I'm using Antd Datepicker in my website. We get an array of numbers representing disabled dates from an external api and show only the dates in the datepicker(no month, year etc). The date selection is for a monthly subscription and the user just sele ...

Leverage the model attribute in a Spring controller to conditionally display elements using

I am currently working with spring boot, angularjs and using html as the view. This setup is being implemented in index.html. <a ng-show="permission=='write'"> By returning the 'permission' value in the model from the spring boo ...