Tips for modifying multiple divs with the same class using querySelector

I am curious about how to change the class on multiple divs at once using JavaScript. In the example below, only the first use of the class is recognized, while all subsequent ones are ignored. querySelectorAll does not seem to work. Thank you in advance.

function setZoom(color) {
document.querySelector('.var').style.color = color;
  }
.var {
  margin-top:20px;
  color:black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>



<label for="input1" value="green" onclick="setZoom('blue')">
  <button>green</button>
</label>

<label for="input2" value="red" onclick="setZoom('yellow')">
  <button>btn-yellow,</button>
</label>

<label for="input3" value="pink" onclick="setZoom('pink')">
  <button>btn-pink</button>
</label>
            
            
<div class="var">
  content div 1
</div>
<div class="var">
  content div 2
</div>
<div class="var">
  content div 3
</div>

Answer №1

To achieve this effect, you can utilize the querySelectorAll method to retrieve a nodelist of elements. Next, you can loop through these elements using the forEach function and apply style changes as needed.

function setZoom(color) {
  document.querySelectorAll('.var').forEach((item) => {
    item.style.color = color;
  })
}
.var {
  margin-top: 20px;
  color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label for="input1" value="green" onclick="setZoom('blue')">
  <button>green</button>
</label>

<label for="input2" value="red" onclick="setZoom('yellow')">
  <button>btn-yellow,</button>
</label>

<label for="input3" value="pink" onclick="setZoom('pink')">
  <button>btn-pink</button>
</label>

<div class="var">
  content div 1
</div>
<div class="var">
  content div 2
</div>
<div class="var">
  content div 3
</div>

Answer №2

I believe a modification is needed in this scenario,

function updateStyle(color) {
document.querySelector('.var').style.color = color; 
}

Change it to the following code snippet:

function updateStyle(color) {
document.querySelectorAll('.var').style.color = color; 
}

The querySelector function will target only one specific element, while the querySelectorAll function will target all elements that match the specified criteria.

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

Incorporate a variable from an HTML form into PHP for FPDF functionality

How can I retrieve a variable from an "input" element in another HTML file? <input type="text" id="client" name="clientTest" required minlength="1" maxlength="30" size="30"> I need to pass this variable to my PHP file for FPDF. It seems like I hav ...

Set the input of a component in Angular to determine its width

I am working on a basic angular component. Here is the code snippet: <div class="k-v-c" fxFlex fxLayout = "row" > <div class="k-c" fxFlex = "widthOfTable" > {{ key | translate }} </div> < div class="separator" > ...

Pausing THREE.js animations when idle

As I work on my React app using THREE.js, I find myself working with two key components: a carousel scene created in THREE.js and a full-screen overlay scene. When the overlay scene is active, I want to pause the carousel scene since it is not visible. Cu ...

How can jQuery identify the elements that the selected text spans across?

In the midst of a project, I find myself in need of extracting specific text within an iframe. This text may traverse across multiple spans within the iframe, each identified by a unique ID spanning from 1 to the end of the page. My goal is not to retrie ...

Experiencing the 'Page prerendering error' message within Next.js

I encountered a prerender error during the deployment phase that I'm struggling to comprehend: Error occurred prerendering page "/about". Read more: https://nextjs.org/docs/messages/prerender-error ⨯ useSearchParams() should be wrapped in ...

The click event listener declared with v-on inside a Vue Component fails to trigger

I am currently working on a Vue instance for a sidebar within my application that displays a list of menu items. In order to achieve this, I have created a local component with the following template structure: template:'<div><li class="cust ...

What is the best way to extract information from an embed?

As I work on creating a suggestion command, I am faced with the challenge of editing the message with a "-approve <The message id>" command. The issue arises when attempting to retrieve information from the message using: const Suggestionchannel = cl ...

How can I use variables to show the second dropdown list only when a value has been selected in the first dropdown?

Is there any way I can choose a specific value from a dropdown list and based on that selection, show another dropdown list? I understand how to do it with regular words, but what if I use variable names? University Name: <select name="university" id=" ...

Troubleshooting problem with Angular ngx-bootstrap datepicker positioning on mobile devices

Having an issue with ngx-bootstrap/datepicker, it works fine on larger screens but not on mobile screens. Any assistance would be appreciated. https://i.sstatic.net/ZGdyQ.png When the screen size is reduced to mobile (even on actual mobile devices), it o ...

Condensing an Array of Objects into a solitary result

Hey there, I'm currently exploring the most efficient method to accomplish a task. The data I am dealing with looks something like this: [ { name: 'email.delivered', programme: 'Email One', timestamp: 2022-03-24T18: ...

The reason behind the successful execution of the final .then in promise chaining

I am new to JavaScript and have encountered an interesting problem with the following code. Even though I haven't returned anything from the .then method, the last .then (blue color) works instead of the first one (red color). Can someone explain why ...

Struggling with the migration of routes from react-router v3 to v4

My route configuration using react-router v3 is as follows: <Route component={App}> <Route path="login" component={Login} /> <Route path="logout" component={Logout} /> <Route path="/" component={Admin}> <IndexRoute com ...

Designing a user-friendly search form using HTML

As a beginner in coding, I am attempting to set up a search form using basic HTML on a webpage. Unfortunately, I am facing difficulties in processing the results properly due to my limited understanding of certain terms. Here is my desired outcome: http: ...

Automatically update the version of the appcache manifest file

After enabling application cache for my web application, I want to ensure that the cache manifest file's version is automatically updated every time I generate the war or deploy the application. This will ensure that the browser fetches content from t ...

Endless cycle within the while loop without any obvious cause

I've been tinkering with a timer and thanks to some feedback I received in this community, everything is running smoothly. Here's what the current version looks like for reference: https://i.stack.imgur.com/Qd7ll.png Here's a snippet of my ...

Tips on utilizing CSS for text transformations

I'm currently working on a web app where I am using the CSS "transform" property to rotate text by 90 degrees on large and desktop screens. However, I would like the rotation angle to automatically change to 0 degrees if the screen size is small. Can ...

Why is it that I cannot use the .get method on JSON data? And what is the best way to convert JSON into a map?

I'm currently in the process of creating a test for a function that accepts a map as an argument, Under normal circumstances when the code is executed outside of a test, the parameter would appear like this (when calling toString): Map { "id": "jobs ...

What is the best location to upload a contract in order to avoid errors from undefined methods when accessing

Attempting to execute a method from my smart contract on the ropsten test network has led me to an error within my getBalance() function: Unhandled Runtime Error TypeError: Cannot read properties of undefined (reading 'methods') 46 | asy ...

What are the best techniques for streamlining nested objects with Zod.js?

As a newcomer to zod.js, I have found that the DataSchema function is extremely helpful in verifying API data types and simplifying the API response easily. However, I'm curious if there is a way to streamline the data transformation process for myEx ...

Switch out the smaller thumbnail image with a more enlarged image

Im pretty new to web programming and im working on a site now. In one part of this site, I have collections of 3 pictures. 1 larger one and two smaller thumbnails below it. The goal is to create a way in which i can click on one of the thumbnails and the ...