The class styling is malfunctioning

When I click the 'night' button, I want the word color in the class=css to change to white. However, this is not working as intended, even though all other word colors are changing correctly.

Here is my code:

.css {
      font-weight: bold;
      color: pink;
    }
    #first {
      color: lightblue;
    }
    span {
      font-weight: lighter;
      color: green;
    }
<input type="button" value="night"
                onclick="
                    document.querySelector('body').style.backgroundColor = 'darkblue';
                    document.querySelector('body').style.color = 'yellow';
                    document.querySelector('.css').style.color = 'white';
                    document.querySelector('#first').style.color = 'orange';">

            <input type="button" value="day"
                onclick="
                    document.querySelector('body').style.backgroundColor = 'white';
                    document.querySelector('body').style.color = 'black';
                    document.querySelector('.css').style.color = 'pink';
                    document.querySelector('#first').style.color = 'lightblue';">

            <h1><a href="index.html">WEB</a></h1>
            <h2 style="background-color:lightblue; color:Tomato;">CSS</h2>
            <span id="first" class="css">CSS</span> is a language that describes the style of an HTML document.
            <span class="css">CSS</span>  describes how <span>HTML</span> elements should be displayed.
            This tutorial will teach you <span class="css">CSS</span>  from basic to advanced.

Answer №1

As mentioned by others, while document.querySelector() selects only one element (the first it finds), document.querySelectorAll() will find all elements. However, there is a better approach in this case.

It is recommended to use event listeners instead of inline event handlers. Toggling a class (as done on the body) is more efficient and preferred over changing inline styles.

Here's how you can simplify it:

document.querySelector('input[value="night"]').addEventListener('click', function() {
  document.querySelector('body').classList.add('night');
});
document.querySelector('input[value="day"]').addEventListener('click', function() {
  document.querySelector('body').classList.remove('night');
});
.css {
  font-weight: bold;
  color: pink;
}

#first {
  color: lightblue;
}

span {
  font-weight: lighter;
  color: green;
}

body.night {
  background-color: darkblue;
  color: yellow;
}

.night .css {
  font-weight: bold;
  color: white;
}

.night #first {
  color: orange;
}

.night span {
  font-weight: lighter;
  color: ;
}
<input type="button" value="night">
<input type="button" value="day">
<h1><a href="index.html">WEB</a></h1>
<h2 style="background-color:lightblue; color:Tomato;">CSS</h2>
<span id="first" class="css">CSS</span> is a language that describes the style of an HTML document.
<span class="css">CSS</span> describes how <span>HTML</span> elements should be displayed. This tutorial will teach you <span class="css">CSS</span> from basic to advanced.


You can achieve the same functionality with just one button

document.querySelector('input[type="button"]').addEventListener('click', function() {
  this.value = (this.value == 'Night') ? 'Day' : 'Night';
  document.querySelector('body').classList.toggle('night');
});
.css {
  font-weight: bold;
  color: pink;
}

#first {
  color: lightblue;
}

span {
  font-weight: lighter;
  color: green;
}

body.night {
  background-color: darkblue;
  color: yellow;
}

.night .css {
  font-weight: bold;
  color: white;
}

.night #first {
  color: orange;
}

.night span {
  font-weight: lighter;
  color: ;
}
<input type="button" value="Night">
<h1><a href="index.html">WEB</a></h1>
<h2 style="background-color:lightblue; color:Tomato;">CSS</h2>
<span id="first" class="css">CSS</span> is a language that describes the style of an HTML document.
<span class="css">CSS</span> describes how <span>HTML</span> elements should be displayed. This tutorial will teach you <span class="css">CSS</span> from basic to advanced.

Answer №2

querySelector is designed to select a single element at a time. So, when you use document.querySelector('.css') and modify its style, you are affecting only one element.

To handle multiple elements with the class name of 'css', it's better to utilize querySelectorAll along with forEach for iteration:

.css {
  font-weight: bold;
  color: pink;
}

#first {
  color: lightblue;
}
  
span {
  font-weight: lighter;
  color: green;
}
<input type="button" value="night" onclick="
    document.querySelector('body').style.backgroundColor = 'darkblue';
    document.querySelector('body').style.color = 'yellow';
    document.querySelectorAll('.css').forEach(elm => elm.style.color = 'white');
    document.querySelector('#first').style.color = 'orange';
    ">
<input type="button" value="day" onclick="
    document.querySelector('body').style.backgroundColor = 'white';
    document.querySelector('body').style.color = 'black';
    document.querySelectorAll('.css').forEach(elm => elm.style.color = 'pink');
    document.querySelector('#first').style.color = 'lightblue';
    ">
<h1><a href="index.html">WEB</a></h1>
<h2 style="background-color:lightblue; color:Tomato;">CSS</h2>
<span id="first" class="css">CSS</span> is a language that describes the style of an HTML document.
<span class="css">CSS</span> describes how <span>HTML</span> elements should be displayed. This tutorial will teach you <span class="css">CSS</span> from basic to advanced.

Inline handlers like eval can introduce security risks. It's advised to avoid them and instead properly attach event listeners in JavaScript:

document.querySelector('input[value="night"]').onclick = () => {
  document.querySelector('body').style.backgroundColor = 'darkblue';
  document.querySelector('body').style.color = 'yellow';
  document.querySelectorAll('.css').forEach(elm => elm.style.color = 'white');
  document.querySelector('#first').style.color = 'orange';
}
document.querySelector('input[value="day"]').onclick = () => {
  document.querySelector('body').style.backgroundColor = 'white';
  document.querySelector('body').style.color = 'black';
  document.querySelectorAll('.css').forEach(elm => elm.style.color = 'pink');
  document.querySelector('#first').style.color = 'lightblue';
}
.css {
  font-weight: bold;
  color: pink;
}

#first {
  color: lightblue;
}
  
span {
  font-weight: lighter;
  color: green;
}
<input type="button" value="night">
<input type="button" value="day">
<h1><a href="index.html">WEB</a></h1>
<h2 style="background-color:lightblue; color:Tomato;">CSS</h2>
<span id="first" class="css">CSS</span> is a language that describes the style of an HTML document.
<span class="css">CSS</span> describes how <span>HTML</span> elements should be displayed. This tutorial will teach you <span class="css">CSS</span> from basic to advanced.

Answer №3

When targeting multiple elements, it is recommended to use querySelectorAll instead of querySelector.

I also suggest separating the js from the css, as shown below.

function changeCssClassItemsColor(color) {
  const cssItems = document.querySelectorAll('.css');

  cssItems.forEach(function(item) {
    item.style.color = color;
  });
}

function switchToNight() {
  document.querySelector('body').style.backgroundColor = 'darkblue';
  document.querySelector('body').style.color = 'yellow';
  document.querySelector('#first').style.color = 'orange';

  changeCssClassItemsColor('white');
}

function switchToDay() {
  document.querySelector('body').style.backgroundColor = 'white';
  document.querySelector('body').style.color = 'black';
  document.querySelector('#first').style.color = 'lightblue';

  changeCssClassItemsColor('pink');

}
.css {
  font-weight: bold;
  color: pink;
}

#first {
  color: lightblue;
}

span {
  font-weight: lighter;
  color: green;
}
<input type="button" value="night" onclick="switchToNight()">

<input type="button" value="day" onclick="switchToDay()">

<h1><a href="index.html">WEB</a></h1>

<h2 style="background-color:lightblue; color:Tomato;">CSS</h2>

<span id="first" class="css">CSS</span> is a language that describes the style of an HTML document.

<span class="css">CSS</span> describes how <span>HTML</span> elements should be displayed. This tutorial will teach you <span class="css">CSS</span> from basic to advanced.

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

Tips on effectively centering a wide div

After much experimentation, this is what I came up with: (function(d, s, id) { var js, fjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) return; js = d.createElement(s); js.id = id; js.src = "//connect.facebook.net/en ...

Chrome mistakenly identifying octet-stream as a .png image

My application incorporates the use of Google Maps API V3 and ASP.Net, utilizing OverlayView to customize icons on the map. The icon's image is configured within the onAdd event by dynamically adjusting the background CSS property using JavaScript. T ...

Revamp State before redirecting using React Router Dom

In my current project, I am facing an issue with redirecting after updating the state successfully. The technologies I'm using include React 16.12.0 and React Router DOM 5.1.2. Here's the scenario: I have a button that, when clicked, should updat ...

Sorting method in Ext JS 6.2.0 using mode

Seeking clarification on the sort([field],[direction],[mode]) method in Ext JS 6.2.0. Can someone explain the distinction between append, prepend, replace, and multi as mentioned in the documentation available at this link? I am unable to find a clear expl ...

Display information in real-time based on user input using Highcharts

I am trying to display data using highcharts on my index.php page. Can anyone help me with this?, here is what I have attempted so far: This is the HTML code I have: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" cont ...

Using Radio button to access local HTML pages - A step-by-step guide

I am currently working on a project that involves the use of radio buttons and their corresponding options. My goal is to have each radio button selection lead to a specific HTML page being displayed. I've come across solutions involving external URLs ...

How to apply a CSS class to the body element using Angular 2

I am working with three components in my Angular application: HomeComponent, SignInComponent, and AppComponent. The Home Page (HomeComponent) is displayed when the application is opened, and when I click the "Sign In" button, the signin page opens. I want ...

What is the best way to generate a live map with constantly updating markers?

Is it possible for me to learn how to develop a live map similar to the one on this site: www.lightningmaps.org? It's fascinating to watch new markers pop up every few seconds. I'm interested in building a real-time map that can track IP locatio ...

Removing jQuery error label from an HTML block

I need a single command that will remove an error label from my HTML when the field content is changed. It currently works on input and select elements, but not within an input-group. I am looking for a solution that will work universally across all instan ...

Exploring the realms of development and production with Next JS and Vercel

I've recently developed a movie database application using Next JS to explore its functionality. This app allows users to create, read, update, and delete data in Firebase by utilizing the API endpoints provided by NextJS. While the app works smoothl ...

Could the slow loading time of the React site be attributed to an overload of static assets?

As a ML professional diving into frontend development, I have recently incorporated various fixed assets such as images into the assets folder for React. However, I've noticed that my website is running slower than expected. Do you believe that these ...

Method for creating a randomized layout grid in MaterialUI where each row contains a total of three columns

In the process of developing a React application that interacts with the reddit api and oAuth. Utilizing MaterialUI, I am currently experimenting with the Component to create a 3 column grid of images with dynamically generated column widths, maxing out a ...

Blend the power of Dynamic classes with data binders in Vue.js

Recently, I've been working on a v-for loop in HTML that looks like this: <ul v-for="(item, index) in openweathermap.list"> <li>{{item.dt_txt}}</li> <li>{{item.weather[0].description}}</li> <li>{{item.w ...

Broadcast signals to an overarching frame

I have successfully embedded a chatbot (Angular 14 app) in an iframe and now I need to determine whether the frame should be minimized so it can fit within the parent container. My goal is to send custom events to the receiving frame. let iframeCanvas = do ...

Having trouble with the page layout in AngularJS

I am currently delving into Angular JS in order to fulfill some academic requirements. The issue I am facing is with the rendering of a landing page after successfully logging in through a login portal that caters to three types of users. Strange enough, w ...

Difficulty encountered with fetching results using jQuery autocomplete with AJAX as the data source

My autocomplete feature is not working properly with my ajax data source. Here is my code: $("#id_q").autocomplete({ source: function (request, response) { $.ajax({ url: "/search/autocomplete/", dataType: "jsonp", ...

Assistance in using jQuery to locate specific div elements is

I am currently working on creating a navigation bar that features icons triggering contextual submenus upon hover. The main idea is that hovering over an icon will display a popup menu or tooltip with additional options, while still allowing the icon itsel ...

Acquiring information from a variable via an HTTP request

I am new to making http requests and using PHP. I have a code snippet that makes an AJAX call: xmlhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var doc = xmlhttp.response; myFunc( ...

Middleware in Express can be executed more than once

I am encountering a frustrating issue where my middlewares are being called multiple times without explanation. Despite having written short and simple code while learning Express and Node, I cannot pinpoint the reason for this behavior. I find it confusin ...

Using Javascript to Pass Variables to Ajax with getElementById

Struggling to figure out how to effectively pass a Javascript Variable to Ajax and then post it to PHP? While both the Javascript and PHP code are functioning as expected, the challenge lies in transferring the Javascript Variable to Ajax for subsequent ...