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

Module specifiers that are considered relative must always commence with either "./", "../", or just "/"

I need help with importing three.js. I have been following the documentation but I keep encountering an error message: Uncaught TypeError: Error resolving module specifier “three”. Relative module specifiers must start with “./”, “../” or “/ ...

Tips for resolving Vue.js static asset URLs in a production environment

I included the line background-image: url(/img/bg.svg); in my CSS file. During development mode, this resolves to src/img/bg.svg since the stylesheet is located at src/css/components/styles.css. However, when I switch to production mode, I encounter a 40 ...

Update the URL using JQuery and Ajax without having to reload the page, ensuring compatibility with Internet Explorer versions 8 and 9

Upon the initial loading of my webpage, it directs to the following URL: /default/ After clicking the "nextPost" button on the screen (which includes an attribute named data-nextPostNumber), the corresponding code is as follows: event.preventDefault(); ...

Dynamic resizing navigation with JQUERY

I have successfully created a navigation menu that dynamically resizes each list item to fit the entire width of the menu using JavaScript. $(function() { changeWidth(500); function changeWidth(menuWidth){ var menuItems = $('#menu l ...

Having trouble getting Material-UI radio buttons to cooperate with react-final-form

After successfully implementing my material-ui radio button, I encountered issues when integrating it with react-final-form. The problem now is that the radio button is no longer clickable. However, upon removing the ...input inside inputProps, the radio b ...

Tips for adding an icon to an image using PHP and CSS

My goal is to create a responsive image gallery where each image has an icon or text that allows me to delete it if necessary. Here is my HTML and PHP code: <?php $sqlimage = "SELECT * FROM images where `id_user` = '".$customer_id."'"; ...

Using vanilla JavaScript with AJAX, the second asynchronous post will only be sent once the first post has been successfully sent

I am in the process of creating a HotSpot that offers internet access once users input their email addresses. To make this function properly, I need to execute two separate AJAX posts: The first one sends hidden username and password details to the rout ...

Exploring the Benefits of Utilizing External APIs in Next JS 13 Server-side Operations

Can someone provide more detail to explain data revalidation in Next JS 13? Please refer to this question on Stack Overflow. I am currently utilizing the new directory features for data fetching in Next JS 13. According to the documentation, it is recomme ...

What distinguishes running rm -rf node_modules + npm i from using npm ci?

When using a Unix system and needing to clean out the node modules folder, is there any benefit or distinction between executing rm -rf node_modules followed by npm i as opposed to npm ci My understanding is that both yield the same outcome, but is th ...

JavaScript's functionality akin to PHP's exec() function

I am searching for a way to run a shell command through javascript, similar to the functionality of PHP's "exec()" function. I understand that executing shell commands in javascript may not be recommended due to security concerns. However, my javascri ...

Interact with jQuery to trigger events upon clicking on a list item, excluding checkboxes within the list

I'm in the process of developing a straightforward web application. I have a dynamically generated list on one section: Subsequently, I set up an event that triggers when any element within the list is clicked: $(document).on('click', &apo ...

Using SimplyJS and XML: extracting the value of a specific key

Hey there, I wanted to update you on my progress with the Pebble Watch project. I've switched over to using an official external API to make HTTP requests for values, and now I'm receiving results in XML format instead of JSON. Here's a ...

What is the preferred choice: using camelCase in CSS with Styled Components or Emotion for standard React development?

When I'm coding with React Native, I use the styled properties that follow most of CSS syntax and are formatted in camel case. For instance: //... <Component style={styles.container} /> //... const styles = StyleSheet.Create({ ...

Display fewer search results initially and have the option to view more when hovering

I am working with a PHP function that generates a ul element. <ul> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> <li>Item 4</li> <li>Item 5</li> I am looking to display the list in a li ...

Incorporate a smooth infinite scroll feature in a CSS carousel that seamlessly loops without

Looking for a solution to the carousel jerk issue when it reaches the end of the loop? Is there a way to seamlessly loop start without any noticeable interruptions? Here is the code in question. Avoiding the use of JavaScript, is there a method to achieve ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

transferring data from one HTML file to another using a loop with technologies such as HTML,

As a beginner in front end development, I am finding it a bit challenging at the moment. Here's what I have so far: 1 main HTML file (index.html) 1 JavaScript file (something.js) 2nd HTML file (something.html) Main HTML: <!DOCTYPE html> < ...

Press on a specific div to automatically close another div nearby

var app = angular.module('app', []); app.controller('RedCtrl', function($scope) { $scope.OpenRed = function() { $scope.userRed = !$scope.userRed; } $scope.HideRed = function() { $scope.userRed = false; } }); app.dire ...

Adjust the spacing of a div based on the fluctuating height of another dynamically changing div

Is it possible to dynamically adjust the margin of a div using jQuery or JS? Currently, I have set a margin on a div by calculating the height of a container that includes images. var articleImageHeight = $('.slides_control').height(); $(' ...

Struggling to Create a Survey with Included Message: Error - Unable to Initialize MessageEmbed

I'm attempting to create a poll feature for my discord bot that displays both the poll question and results as an embedded message. While I've managed to get the poll information in plain text format, I'm encountering an error when trying to ...