Using Javascript to update various element styles using their corresponding IDs

I am currently working on implementing a dark mode feature and I am encountering an issue when trying to change the CSS of multiple elements at once.

This is my JavaScript code:

      var elem = document.getElementById('fonts');
      for(var i=0; i<elem.length; i++){
        elem[i].style.color="#FFFFFF";
        console.log(elem[i]);
      }

However, nothing seems to be changing. I believe I need to use a loop because there are multiple elements with the same id "fonts". If I try without the loop, only the first one gets affected.

The console isn't showing any errors either. Was there something wrong with how I implemented this?

Answer №1

It seems like you may be approaching this in the wrong way. Instead of using the same id for multiple elements, you should consider using a class instead.

Here is an example to demonstrate:

document.getElementById("btn").addEventListener("click", function() {
  var elem = document.querySelectorAll('.fonts');

  for(var i=0; i<elem.length; i++){
    elem[i].style.color = "#00aeff";
    console.log(elem[i]);
  }
});
* { margin: 0; padding: 0; }
<h1 class="fonts">Heading1</h1>
<p class="fonts">Paragraph</p>
<span class="fonts">Span</span>
<div class="fonts">Div</div>

<button id="btn">Change</button>

Remember that the CSS and button included in this example are not necessary; they are just for illustration purposes. You can use querySelectorAll to target all elements with the same class and then loop through them using a for loop.

Answer №2

using the <div id="fonts"> more than once in your HTML will cause issues with your code.

  1. Replace ids with classes

  2. Consider using HTML DOM's "querySelector" instead of "getElementById".

For an id, follow this syntax:

var elem = document.querySelector("#fonts");

For a class, use this syntax:

var elem = document.querySelector(".fonts");

Answer №3

One way to enhance the readability and simplify the code is by utilizing the for...of statement.

document.getElementById("btn").addEventListener("click", function() {
  let elem = document.querySelectorAll('.fonts');

  for (let font of elem) {
    font.style.color = "#00aeff";
  }
});
* {
  margin: 0;
  padding: 0;
}
<h1 class="fonts">Heading1</h1>
<p class="fonts">Paragraph</p>
<span class="fonts">Span</span>
<div class="fonts">Div</div>

<button id="btn">Change</button>

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

Having trouble with Next.js and Next-auth? When I make an HTTP request in getServerSideProps, getSession is returning null in my secured API Route

I am currently working on securing an API Route that is being called from both the Client and Server-side on different pages. When accessing the test page, it returns a 401 error. However, when accessing the test2 page, the content is retrieved successfu ...

React and Material UI: troubleshooting problems with layout columns

I'm working on a project with three columns and I want to include a column for removing each row. Is it possible to add a "removing" column on the right? If so, how can I go about doing it? VIEW CODESANDBOX: HERE const CustomTableRow = ({ row, index ...

How can I position an element to the bottom right using CSS?

Is there a way to position this element to the bottom right corner? HTML <div class="info player"> <div id="job" style="display:none;"><span>Jobname</span></div> <div i ...

I aim to toggle the visibility of input fields upon clicking a button

Form.html <form [formGroup]="myForm"> <ion-button [(ngModel)]="isActive"(click)="onClick()" >Add</ion-button> <ion-item> <ion-label position="floating">First Name</ion-label&g ...

Can you explain the distinctions among 'data:', 'data: ()', and 'data()' when working with Vue.js?

While exploring the Vue.js documentation, I came across two ways to define data: data: {} and data() { return; }. data: { defaultLayout: 'default' } data() { return { defaultLayout: 'default' } } However, there is ...

What advantages does the Step function (AWS) offer compared to setTimeout (Javascript) for scheduling tasks?

I am currently in the process of developing an API service that allows any client to provide me with their HTTP request along with the desired time in seconds for execution. I have considered two potential approaches to achieve this: Utilizing a lambda f ...

Issue encountered when running a minification build on Angular 5

After successfully updating my Single Page Application (SPA) from Angular 4 to Angular 5 along with all dependencies, everything seemed to be working well. Both the development and production builds were functioning without any errors or warnings. However ...

Arrangement of 3 columns on the left and 1 column on the right using flex-box layout

My goal is to utilize flexbox in conjunction with bootstrap 4 to produce a design featuring 3 vertically stacked columns on the left, accompanied by a single column on the right that matches the height of the left columns. Following that, there will be som ...

A div element with a z-index of 9 remaining below another element with a z-index of 1

Even with a higher z-index, my <h4> and <a> elements are not visible above the background. <section class="no-padding main-slider mobile-height wow fadeIn"> <div class="swiper-full-screen swiper-container height-100 width-100 whit ...

Show two spans, each underneath the other

I am looking to showcase two span elements, one below the other. Take a look at my HTML code snippet <img class="profile-photo margin-0" data-ng-if="!question.isOpen" ng-src="{{question.profilePicId ? que ...

Disable audio playback on tab unfocus using Javascript/HTML

Is there a way to automatically mute a tab or video when it is not in focus? As a beginner, I am unsure how to accomplish this task. The audio source is currently a webm file embedded within a <video> tag. ...

I have been tirelessly attempting to resolve this issue, yet all my efforts have proven futile thus

Encountering an issue with web packs and nextjs. import NextDocument, { Html, Head, Main, NextScript } from 'next/document' import theme from '../libs/theme.js' export default class Document extends NextDocument { render() { retu ...

How can I fetch and reference multiple local JSON files in Vue using Axios?

I am currently utilizing vue for prototyping some HTML components. Is there a method to make Vue detect two separate JSON files? vue.js var vm = new Vue({ el: '#douglas-laing', data: { products: [], contentPanels: [] }, created() ...

Is it possible to launch a Nextjs app on Vercel for production purposes? How well does it handle high volumes of traffic?

As a newcomer to Nextjs, I am looking to deploy my app to production. I'm curious about whether Vercel can effectively handle heavy traffic on the site. Should I consider utilizing platforms such as AWS or GCP for deployment instead? Any advice would ...

Dynamic loading of JavaScript/HTML content using jQuery Mobile and PhoneGap

I am currently in the process of building a mobile app using Dreamweaver CS6 (with PhoneGap), along with jQuery Mobile and JavaScript. This app aims to gather user-inputted form data, convert it into a JSON object, and send it to a python web service. The ...

Ways to generate arrays in Typescript

My dilemma lies in a generator method I've created that asynchronously adds items to an array, and then yields each item using yield* array at the end of the process. However, TypeScript compiler is throwing me off with an error message (TS2766) that ...

How to implement form modal binding using Laravel and Vue.js

There are two models named Tour.php public function Itinerary() { return $this->hasMany('App\Itinerary', 'tour_id'); } and Itinerary.php public function tour() { return $this->belongsTo('App\Tour', ...

Selecting options on hover, either A or B at the least

I need a jQuery selector to handle an 'either' scenario. Specifically, I have a dropdown menu and want it to stay open when the user hovers over either of two elements. Either when they hover over the button or when they leave the popped-out men ...

Having trouble with NVM not working correctly in Ubuntu 21.04 Terminal?

Lately, I've been facing challenges with updating my Node.js version, and one method I tried was using node version manager. After downloading the install_nvm.sh file with the command curl -sL https://raw.githubusercontent.com/nvm-sh/nvm/v0.38.0/insta ...

What is the proper way to employ if and else if statements within Angular2?

Here's a question that has been duplicated on my How to utilize *ngIf else in Angular? post! ...