Pressing a button to alter the text color

While experimenting, I attempted to alter the text color of my HTML using JavaScript. After a few attempts, I came to the realization that I cannot change the color if I am already changing it in CSS. Does this mean CSS is executed at the end? Also, how can I change the color of the text after clicking a button if I am also changing it in CSS? I apologize for my lack of experience in this area.

function changecol()
      { 
          var html=document.body;

          html.style.backgroundColor='black';
          html.style.color='white';

      }

I expected all the lines in my HTML to turn white, but only those where I had not applied CSS became white.

Answer №1

Here is a simple jQuery method to change the background color and text color when a button is clicked:

$("#butt").on("click",function(){
          $(".color").css("background-color","red");
          $(".color").css("color","white");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="color">HELLO</div>
<button id="butt">Change Color</button>

Answer №2

It seems like the issue you're facing could be related to inheritance. Specifically, when you set a style on the body element, only elements that do not have their own styles will inherit it. To resolve this, one solution is to apply the style directly to each individual element.

Here's a suggestion:

function updateStyles(){
  document.body.style.backgroundColor='black';
  document.body.style.color='white';

  // Update background color for each element 
  var elements = document.querySelectorAll('*');
  for(let i=0;i<elements.length;i++){
    elements[i].style.backgroundColor='black';
    elements[i].style.color='white';
  }
}

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

Creating an AngularJS service or factory that dynamically compiles HTML using a variable from the $scope

Looking to streamline a commonly used function in various controllers within an AngularJS project by creating a service/factory that can be accessed through $rootScope. The objective is to refactor the existing function: $scope.twitterRefresh = function(o ...

executing npm tasks concurrently

Trying to demonstrate running npm tasks in parallel is my current task. I should be able to achieve this using "&" for parallel and "&&" for series. { "name": "npm", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "co ...

Encountering an issue while attempting to fetch a value from a nested object property with VueJS Interpolation

I'm struggling to properly display nested arrays in Vue JS. Below is a snippet of my JSON data: { "id": 1, "slug": "test-page", "banner": { "title": "banner title", "subTitle": "my sub title", "hasSubTitle": false, "hasClass": " ...

reasons why the console is not logging updated states

I'm having trouble logging the updated state values after using setState. The values seem to be updating fine in the render function, but not in the tokenAccess() method. Can anyone explain why this is happening? import React, { Component } from &apo ...

Navigating through Vue Router with Dynamic Imports and Guards

I am looking to dynamically bring in data from a component file into a router file, and then allow the use of next() based on the value of the imported data. In my App.vue file, I am using this.$router.push({name: "Dashboard"}) when the data changes from ...

Converting the stage object to JSON format and incorporating it into an HTML5 environment using

$("#show").click(function(){ var stage = Kinetic.Node.create(json, 'container2'); var ball = new Image(); var cone = new Image(); var tshirt = new Image(); ball.onload = function() { stage.get('.ball').apply ...

Jquery Error in Bootstrap and DataTables Integration

My knowledge of frontend coding is limited, so please bear with me. Initially, my website was using MVCContrib grid along with its own CSS style. Recently, I switched to Bootstrap which caused MVCContrib to stop working. I've been struggling to integ ...

What is the proper way to utilize the value of a Node.js promise in a different function?

In my Node.js application, I have two functions defined. The first function is structured like this: function checkAdd ( address /* : string | void */ ) /* :Promise<Object[]> */ { var convertToLowerCase = address.toLowerCase() return Promi ...

A guide on how to examine the array index within a nested array

Let's consider this scenario with arrays: numbers = [[3,5],[2,4]] elements = [2,4] It seems like the array numbers contains the array elements But when we try to find the index of elements in numbers, it returns -1 Any thoughts on how to tackle th ...

Encountering a Typescript error while attempting to remove an event that has a FormEvent type

Struggling to remove an event listener in Typescript due to a mismatch between the expected type EventListenerOrEventListenerObject and the actual type of FormEvent: private saveHighScore (event: React.FormEvent<HTMLInputElement>) { This is how I t ...

Ways to eliminate the design from a previously selected list item

I'm working on creating a calendar that displays 3 booking times when a user clicks on a specific day. However, I am facing an issue where the styling (green color) remains on the selected day even if the user chooses a different day. Any assistance o ...

Struggling to get the AJAX code functioning correctly

Embarking on my journey with AJAX, I decided to test a simple example from the Microsoft 70515 book. Surprisingly, the code doesn't seem to be functioning as expected and I'm at a loss trying to figure out why - everything appears to be in order. ...

Receiving Array Data from JSON and Listing Results

Once I retrieve the first row result from a JSON array, I want to display all the results using the jQuery each method. Here is the code snippet: $(document).ready(function () { $("#btnsearch").click(function() { valobj = $('#search_box' ...

Customizing Marker Clusters with ui-leaflet: A guide on changing marker cluster colors

I'm trying to customize the markerCluster color in a non-default way. I've been exploring the API and it looks like the recommendation is to modify a divIcon after creation, possibly like this: var markers = L.markerClusterGroup({ iconCreateFunc ...

Consolidate list: Make sure to leave only the currently active item open

For some reason, I am encountering an issue with this code on this platform. The problem is that every time I click on a list title, all items open up instead of just the one I clicked on. Is there a way to modify this code so that only the clicked item ex ...

What is the process of invoking a secondary "external" function with Nodejs, Expressjs, and bluebird?

Struggling with creating a nodejs application, a new area for me. I've managed to work with Promises and fetch data from a database. Take a look at the code below: myModel.js var express = require('express'); var app = express(); var Promi ...

Customizing the active link color in Bootstrap dropdown menus

Is there a way to customize the color and background of an active link in a boostrap's dropdown menu? Despite trying to override bootstrap's @dropdownLinkColorActive and @dropdownLinkBackgroundActive variables, the changes don't seem to tak ...

Tips for managing onClick events within a conditional component

I am currently attempting to implement an onClick event on the data that I have selected from the AsyncTypeahead. My goal is to pass a callback function to the Problem component, which will only render if an item has been selected. However, after selecting ...

What is preventing me from executing this function more than once?

Having this function: const sliderTextChange = document.getElementsByClassName('slider') // text change const changeSliderText = change => { const sliderLeft = document.getElementsByClassName('switch-left') const sliderRight = ...

Retrieve information using Observables just once in Angular 2

One of my Angular 2 components relies on a service that fetches customer data from a Web API and returns an Observable: getCustomers() { return this.http .get(this.baseURI + this.url) .map((r: Response) => { let a = r.jso ...