What is the reason my function is only operating with a single ID?

I'm attempting to create color-changing "squares" that change color when clicked. The first square changes color correctly, but when I click on the others, the color change only happens on the first square.

var image_tracker = 'red';

function changeColor() {
  var image = document.getElementById('red')
  if (image_tracker == 'red') {
    image.style.backgroundColor = "blue";
    image_tracker = 'blue';
  } else {
    image.style.backgroundColor = "red";
    image_tracker = 'red';
  }
}
<div id="red" onclick="changeColor()"></div>
<div id="red" onclick="changeColor()"></div>
<div id="red" onclick="changeColor()"></div>

There are no error messages, it's just not working as I expected :D

Answer №1

It's important for IDs to be unique because the document.getElementById() method will only return the first element it finds. This means it won't know which specific element you clicked on.

To solve this issue, modify your function to accept the image as a parameter. Then, you can use this to reference the exact element that triggered the click event.

var image_tracker = 'red';

function changeColor(image) {
  if (image_tracker == 'red') {
    image.style.backgroundColor = "blue";
    image_tracker = 'blue';
  } else {
    image.style.backgroundColor = "red";
    image_tracker = 'red';
  }

}
<div onclick="changeColor(this)">1</div>
<div onclick="changeColor(this)">2</div>
<div onclick="changeColor(this)">3</div>

Answer №2

If you have a set of buttons that all have similar behavior (clickable, same functionality, etc) labeled as "red", it's best to classify them using a class instead of an id:

var image_tracker = 'red';

/* Iterate all elements with "red" class */
for (const redElement of document.querySelectorAll('.red')) {

  /* Add click event handler */
  redElement.addEventListener('click', function() {
  
    /* Reuse existing click logic but based on redElement instead */
    if (image_tracker == 'red') {
      redElement.style.backgroundColor = "blue";
      image_tracker = 'blue';
    } else {
      redElement.style.backgroundColor = "red";
      image_tracker = 'red';
    }
  });
}
<!-- Define buttons as of the "red" class (and remove the "id") -->
<div class="red">Button 1</div>
<div class="red">Button 2</div>
<div class="red">Button 3</div>

Above, you'll notice that the inline "onclick" has been eliminated from the HTML in favor of the preferred addEventListener() event handling method. Hopefully, this information is helpful!

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

transforming an array into JSON structure using node.js

Hello, I have a list of data that I need to convert into JSON format. Here is an example of how I want the data to look: [ { "slideName": "s0", "imageUrl": "https://s3.amazonaws.com/lifestyle345/testing/slides/cbaa5e650152a0332b494f0074985 ...

Simple HTML/CSS text blocks positioned beside images in a list format

I'm attempting to design a list (ul) where each li has an img on the left and text aligned to the left (including a title and paragraphs) positioned next to the image on the right. I've experimented with float: left and various display propertie ...

Using Regular Expressions to eliminate any characters that are not directly adjacent to numbers (beside specific characters)

My function generates a result that looks like this: given output For comparison, consider the example string below: var string = '    111   1   1\n 1111111 1 \n   &nb ...

Optimizing File Transfers and Streaming Using Next.js and CDN Integration

As I work on developing a download system for large files on my website using Next.js and hosting the files on a CDN, I face the challenge of downloading multiple files from the CDN, creating a zip archive, and sending it to the client. Currently, I have i ...

Page design ruined as a result of oversized fonts in IE9 for <h2> elements

Everything looks great on various browsers, except for the notorious IE9. We've implemented a block-style layout with a width of 660px, centered on the page. Despite setting the h2 width to 660px to match the layout, IE9 displays the font size much ...

Troubleshooting Problem with Accordion Size in CSS

I am facing an issue with a dropdown menu that I have created. The dropdown has parent and child rows to display controls, but the width of the Accordion is not stretching as expected despite being set to 100%. Using Chrome and Edge developer tools, I insp ...

Utilizing getElementsByClassName for web scraping: encountering inaccurate outcomes

I am attempting to extract the inner text from all classes with the className = "disabled" within the provided snippet of HTML Code: HTML code In my effort to achieve this task using MS Access (VBA), the code I have implemented is as follows: Set IE = C ...

When accessing the innerHTML and outerHTML properties on an HTMLElement, they may return undefined without triggering

Task: My goal is to take an HTML string, make changes to certain attributes of image tags within it, and then return the modified HTML string. The function I have developed follows these steps: private resolveImagesInHTML (body: string): string { le ...

Discovering uncategorized elements using javascript

Let's say I have a piece of HTML with some content that is not wrapped in any tags, like this: <html> <body> <p>text in a tag</p> other text outside any tag </body> </html> Is there a way to access the untagged el ...

Tips for inserting an icon alongside a list item in HTML

https://i.sstatic.net/sTWRu.png Can you help me with adding an icon to a list item using Font Awesome or any other method? I want the icon to appear on the right side of the text. I have four sections of text that I want to convert into expandable dropdow ...

Ways to receive a POST request from an external server on a GraphQL Server

Currently, I am working on a project that utilizes GraphQL. As part of the project, I need to integrate a payment processor. When a user makes a successful payment, the payment processor sends a POST request to a webhook URL that should point to my server. ...

assign a variable a value within a function and then retrieve it externally

In order to validate a simple form, I am reading a JSON file and extracting an array from it. My goal is to check if this array contains every single element from a user-generated array, and nothing more. For instance: [1,2,3,4,5] (JSON file array) [1,2,3 ...

Creating separate files for establishing DB connection and writing Node.js queries is a recommended practice for organization

Having an issue with connecting dbconnection.js and demo_api_select.js. When trying to declare a variable in demo_api_select.js, I am encountering errors like this: Error Notification Please assist me in resolving this problem. dbconnection.js: var ...

Tips for restricting the size of uploaded files or the quantity of files in multer express and effectively managing any errors

I am currently working on a code that requires me to set limits on file size or the number of files that can be uploaded. For instance, I want to restrict users from uploading more than 100 files at once or limit the total upload size to 100 mb. However, ...

JavaScript 3D Arrays

Is there a way to create a 3D array similar to runes['red'][0]['test']? If so, how can I accomplish this? var runes = {} runes['red'] = [ 'test': ['loh'] ] runes['blue'] = {} runes[&apo ...

Tips for managing Ajax JSON response in a PhoneGap application

Although there are a few posts on this topic, I am struggling to piece together the necessary components to make it work. I am in the process of converting a web application into an app using phonegap and I am attempting to create a search form that retri ...

When utilizing a JQuery plugin for sliders, Dart does not function in the same way that traditional JavaScript does

Starting out with Dart for Front-End development has been a bit challenging for me. I am trying to incorporate a JQuery plugin called FlexSlider using the Js-Interop Dart Library. However, it's not functioning as expected compared to pure JavaScript, ...

Utilizing MongoDB and Express to access collections within a controller

Is there a way to access the collection in the controller using mongodb and express? I came across this code snippet in the mongodb documentation db.getCollection("countries");, but how do you import the database name: db into a controller? serv ...

Eliminate the display of Last Modified date and file Size in mod_autoindex

Recently, while developing a file storage webpage for my website, I successfully implemented mod_autoindex for my Apache server. However, I now face the challenge of removing the Last Modified and Size fields from the table. I am hopeful that there is a w ...

Attempting to determine which PHP form was submitted

I'm currently working on creating multiple forms within the same page, but I've encountered an issue where the PHP code is not executing properly when attempting to submit the form. <form id="DeleteEmployeeModal" name="DeleteEmployeeModal ...