I am attempting to alter the text style using buttons, but I am encountering difficulty when applying it to multiple instances with the same identifier

Currently, I am attempting to create a button that can toggle a specific style for various sections of my website, such as changing the background colors of certain elements.

While the buttons work correctly when there is only one element in place, I encounter an issue when multiple elements are involved. For instance, if I have thing One and thing Three, the button only affects the first one and not all elements with the same id.

I hope I explained that adequately; I am relatively new to coding and this marks my initial attempt at building a website. So please bear with me on this hahahhaha

var blue = document.getElementById('blue');
function changeBlue() {
  for(var i = 0; i < blue.classList.length; i++) {
    if(blue.classList[i].indexOf('body') >= 0) {
      blue.classList.remove('body');
      blue.classList.add('blue');
    } else { 
      blue.classList.remove('blue');
      blue.classList.add('body'); 
    }
  }
}


var pink = document.getElementById('pink');
function changePink() {
  for(var i = 0; i < pink.classList.length; i++) {
    if(pink.classList[i].indexOf('body') >= 0) {
      pink.classList.remove('body');
      pink.classList.add('pink');
    } else { 
      pink.classList.remove('pink');
      pink.classList.add('body'); 
    }
  }
}
 
.blue { font-family: Helvetica;
        font-size: 18px;
        color: #ffffff;
        background-color:#003eff;
     } 
  
.pink { font-family: Helvetica;
        font-size: 18px;
        color: #ffffff;
        background-color:#eb00ff;
     }

.body { font-family: Helvetica;
        font-size: 18px;
        color: #000000;
        background-color:#ffffff;
     }
 
<button class="body" onclick="changeBlue()">Make Blue</button>
<button class="body" onclick="changePink()">Make Pink</button>

<span class="body" id="blue">thing One</span>
<span class="body" id="pink">thing Two</span>
<span class="body" id="blue">thing three</span>

Answer №1

The problem with the provided code is that it utilizes the same id for multiple elements, which violates JavaScript syntax rules and causes only the code related to the first instance of the id to be executed.

For more information regarding the usage of getElementById, refer to: https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById

To address this issue, I have modified the code by converting the blue identifier into a class for the elements labeled as thing One and thing three. A new class called selected has been introduced to facilitate the addition and removal of the desired color effect. See below for the updated code:

HTML:

<button class="make_blue" onclick="changeBlue()">Make Blue</button>
<button class="make_pink" onclick="changePink()">Make Pink</button>

<span class="body blue">thing One</span>
<span class="body pink" id="pink">thing Two</span>
<span class="body blue">thing three</span>

CSS:

    .blue.selected {
        font-family: Helvetica;
        font-size: 18px;
        color: #ffffff;
        background-color: #003eff;
    }

    .pink {
        font-family: Helvetica;
        font-size: 18px;
        color: #ffffff;
        background-color: #eb00ff;
    }

    .body {
        font-family: Helvetica;
        font-size: 18px;
        color: #000000;
        background-color: #ffffff;
    }

JS:

    function changeBlue() {
        var blueElements = document.getElementsByClassName('blue');
        for (var i = 0; i < blueElements.length; i++) {
            if (blueElements[i].classList.contains('selected')) {
                blueElements[i].classList.remove('selected');
            } else {
                blueElements[i].classList.add('selected');
            }
        }
    }

    function changePink() {
        var pinkElement = document.getElementById('pink');
        if (pinkElement.classList.contains('pink')) {
            pinkElement.classList.remove('pink');
            pinkElement.classList.add('body');
        } else {
            pinkElement.classList.remove('body');
            pinkElement.classList.add('pink');
        }
    }

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

Transfer information to a different division using Ajax

I am attempting to transfer data to another div after an Ajax refresh. Each time it refreshes, new data is fetched from the database. My goal is to retain the old data displayed in the first div, store it, and then move it to the second div when Ajax refre ...

Facing an issue where the CSS class name is not displaying correctly when utilizing CSS Modules with my React

This webpack.config.js file is dedicated to the module section, where loaders are defined for JSX files and CSS. module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'bab ...

Trouble with Bootstrap accordion staying open even after a different one is chosen

Looking for assistance! I am encountering an issue with using jQuery on Bootstrap. The accordion feature is not functioning correctly as it fails to collapse when another section is selected. https://i.stack.imgur.com/uiZPh.png The problem arises when th ...

Disappearing validation message glitch in Chrome HTML5 caused by DOM layering issue?

Currently, I am working on html5 forms and have encountered an issue with a field that has a required attribute set. Upon a user attempting to submit the form, Chrome displays a validation message indicating that the field must not be empty. However, this ...

checkbox value modification and refresh utilizing explode in php

Looking for a solution to the Notice error below: Undefined variable: b in C:\wamp64\www\MyFolder\version1.1\fms\build\english\equipment.php on line 904 Warning: in_array() expects parameter 2 to be array, nul ...

Tips for displaying diverse content in a DIV container when users click on various sections of an image

Apologies for the unclear title, but I'm struggling to explain my technical goal using jargon. The basic concept is this: there will be an image on the webpage, and when a user clicks on a specific area of the image, relevant information will appear ...

What is the best way to change a vertical drop-down menu to a horizontal layout?

I need help aligning my dropdown menu horizontally instead of vertically. I tried using the flexbox example from w3 schools, but it didn't work when I included the classes inside my select tag. Even after debugging, I realized that the issue is with t ...

Display an image from the API that rotates when hovered over with the mouse

Currently, I am fetching data from pokeapi.co and dynamically inserting it into a table. This data includes various stats and an image. My goal is to make the image rotate when hovered over. While creating the table, I added an id="pokeImage" dynamically. ...

Choose a Vue filter according to the variable selected

My Current Table Dilemma Creating a table from a 2D array in Vue2 has been successful for me, as I've managed to display all the values correctly. However, I am facing issues with formatting. The template code is structured like this: <table> ...

gather data from a separate HTML document's form

Within an html file, users fill out a form and database queries are executed to display Google Maps locations. My objective is to store this data in a variable so that it can be used in another html file. This second html file will utilize the previous va ...

Issues with the HTML <div> tag placement in the center

I am encountering an issue while creating a basic HTML website. I want the image and white fields to fill the entire screen (100% width), but they seem to be constrained by some margin on both sides. As a beginner in web development, I believe the solution ...

Conceal the galleryView plugin seamlessly without the need for a

I have implemented jQuery on my webpage to load content without refreshing, displaying only the necessary information. Within the gallery section, there are links for "Other Photography" and "Nude Art". Clicking on these links initializes the gallery with ...

Uploading Files in HTML

My goal is to create a way to input a file using the following method: Input file: <input type="file" name="-f" id="fa"> I would like to include an HTML link (upload example) that, when clicked, will upload an example file without opening the file ...

Adding a background image in Angular is a simple process that can enhance the

Trying to add a background image to my angular application. home-component.html <body> <div style="text-align:center;" class="backgroundimage"> </div> </body> <style> * { margin: 0; ...

Creating a Laravel form with a toggle checkbox for submission

Within the form, there is a toggle switch button. The purpose of this switch button is to determine whether it is in an active or passive state. Upon submitting the form, its value will be "on". My goal is to send this value to the controllers as "passive" ...

[php][html] stuck on trying to solve this error

Any help in figuring out the error on line 37 would be greatly appreciated. I've tried moving the ""; after echo and putting the entire PHP code in an img class="profilePic" src="http://i.imgur.com/ZICYW5z.png"/> and then using echo for the name (I ...

Transforming JSP style tags into CSS declarations

Within my JSP file, I have various tags that look like this: <style type="text/css"> #mask { display: none; cursor: wait; z-index: 99999; position: absolute; top: 0; left: 0; height: 100%; ...

Does Google Chrome have a strange way of interpreting CSS?

Almost done with my website and it looks great on Firefox and IE 8, but Chrome is causing issues. Here's how it appears on FF: And here's Chrome: Notice how Chrome resizes the first image even though the code is the same as the one below? Che ...

Switching videos upon clicking buttons

Hey there! I've got an interesting challenge for you. I have four mp4 videos featuring a cartoon character performing various emotes. My goal is to create a toggle switch that, when activated, will display the first video (intro) along with three butt ...

"Troubleshoot: jQuery UI accordion not functioning properly in response to

I've encountered an issue with the accordion functionality while working with dynamic data. To address this, I'm incorporating JavaScript to generate <div> and <h3> tags for the accordion. Here is the code snippet I am using: $(&ap ...