Attempting to modify the background hue of a grid component when a click event is triggered

I am struggling with the syntax to change the color of an element in my grid when clicked. I have attempted different variations without success. Being new to JavaScript, I would appreciate some gentle guidance if the solution is obvious.

JS

    const gridContainer = document.getElementById('container');

    function makeGrid(rows, cols) {
      gridContainer.style.setProperty('--grid-rows', rows);
      gridContainer.style.setProperty('--grid-cols', cols);

      for (i = 0; i < rows * cols; i++) {
        let cell = document.createElement('div');
        gridContainer.appendChild(cell).className = 'grid-item';
      }
    }
    makeGrid(16, 16);

    const gridElement = document.getElementById('grid-item');
    gridElement.addEventListener('click', () => {
        gridElement.target.style.backgroundColor = 'white';
    })

CSS

:root {
    --grid-cols: 1;
    --grid-rows: 1;
}

#container{
    display: grid;
    grid-gap: 0em;
    grid-template-rows: repeat(var(--grid-rows), 1fr);
    grid-template-columns: repeat(var(--grid-cols), 1fr);
    background-color: black;
}

.grid-item{
    padding: 1em;
    border: 1px solid #131313;
    text-align: center;
}

.grid-item:hover{
    background-color: #ddd;
}

const gridContainer = document.getElementById('container');

function makeGrid(rows, cols) {
  gridContainer.style.setProperty('--grid-rows', rows);
  gridContainer.style.setProperty('--grid-cols', cols);

  for (i = 0; i < rows * cols; i++) {
    let cell = document.createElement('div');
    gridContainer.appendChild(cell).className = 'grid-item';
  }
}
makeGrid(16, 16);

const gridElement = document.getElementById('grid-item');
gridElement.addEventListener('click', () => {
  gridElement.target.style.backgroundColor = 'white';
})
:root {
  --grid-cols: 1;
  --grid-rows: 1;
}

#container {
  display: grid;
  grid-gap: 0em;
  grid-template-rows: repeat(var(--grid-rows), 1fr);
  grid-template-columns: repeat(var(--grid-cols), 1fr);
  background-color: black;
}

.grid-item {
  padding: 1em;
  border: 1px solid #131313;
  text-align: center;
}

.grid-item:hover {
  background-color: #ddd;
}
<div id="container"></div>

I attempted to create a separate function to target and change the color of the grid element upon clicking, but it does not respond to clicks as expected.

Answer №1

Initially, it's worth noting that grid-item is not an element id but rather a class. Therefore, you should utilize getElementsByClassName or querySelectorAll.

Personally, I lean towards using querySelectorAll because it has the flexibility to work with any selector. However, bear in mind that it returns a NodeList, necessitating iteration for applying the click event to each item.

    const gridElements = document.querySelectorAll('.grid-item');

    gridElements.forEach(gridElement => {
      gridElement.addEventListener('click', () => {
        gridElement.style.backgroundColor = 'white';
      })
    })

Answer №2

There are 256 items with the distinctive characteristic of having the class name grid-item, however, they are being accessed by their individual ids. To resolve this issue, consider utilizing the following JavaScript code snippet:

document.querySelectorAll('.grid-item').forEach(item => item.addEventListener('click', () => item.style.backgroundColor = 'white'));

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

The HTML and CSS layout is not displaying correctly as planned

I am currently working on a responsive webpage design project. Here is what I have been experimenting with: jsfiddle <div id="container"> <div id="one">#one</div> <div id="two">#two</div> <div id="three">#t ...

Combining Ionic 3 with epubJS

Greetings. I've been attempting to access ePub files in my Ionic 3 test app without success. epubjs has been installed via npm. Here is the package.json contents: { "name": "app_name", "author": "Author", "homepage": "http://example.com/", ...

Set the CSS/HTML to make two child elements occupy 50% of the height of the parent container div

This task seems deceptively simple, yet I am struggling to find a straightforward solution. Language: (HTML) <div class="col-6-12 subcontent-outer"> <div class="subcontent"> <h1>Header</h1> ...

React-NextJS encountered an error: TypeError, it cannot read the property 'taste' because it is undefined

Recently, I've been encountering an issue with NextJS that keeps throwing the error message: TypeError: Cannot read property 'taste' of undefined. It's quite frustrating as sometimes it displays the expected output but most of the time ...

Transform the binary image data sent by the server into an <img> element without using base64 encoding

It's been a challenge trying to find a reliable method for adding custom request headers to img src, so I'm experimenting with manually downloading the image using ajax. Here is an example of the code I am working on: const load = async () => ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

Exploring the world of Django and JSON POSTs in the realm of Google API mania

Project Overview I am currently developing an application aimed at assisting users in finding rides. My tech stack includes Django, Python 2.7, and integration with Google Maps and Directions APIs. Within a specific view, I present a map where users can ...

Utilizing NodeSize to Optimize the Spacing Among Nodes in the D3 Tree Arr

Currently, I am trying to adjust the positioning of my rectangle nodes because they are overlapping, as illustrated in the image below: In my research, I discovered that D3 provides a nodeSize and separation method. However, I encountered difficulties imp ...

Passing User Authentication State from Express/Passport to a React Client: A Step-by-Step Guide

I want to pass a basic boolean value const isLoggedIn = true; (provided by Passport) from my Express backend to my React frontend. I'm looking for an alternative to embedding it in the HTML through a templating engine. This seems like a common req ...

resetting dropdown selections upon page refresh using jQuery and AJAX

Is there a way to reset or clear the values of two select boxes after refreshing the page in CodeIgniter? Currently, both select boxes retain their values after a refresh. Below is the code I am using: <?php echo form_dropdown('cat_id', $ ...

jQuery text alignment breaking bug

I am attempting to create an overlay for a couple of my divs to prevent users from progressing without completing previous tasks. The overlay is functioning correctly and the message is displaying, but I encounter issues when trying to center the message. ...

How can I extract the "href" attribute from an anchor tag using XPath?

I am working with HTML code that looks like this: <a href="/images/big_1.jpg" class="class-a"> <img class="class-img" src="/images/small_1.jpg"/> <span class="class-span"> <img src="/images/img_1.png"> </ ...

Customize DataTables selector by modifying its frame, font, and alignment

I'm experiencing issues with customizing the page selector in DataTables. Although I managed to change the background color to black, the frame around it remains blue. The font color of unselected pages and the "Next" button also do not reflect the c ...

A comparison between Buffer.byteLength and file size

I'm facing an issue with file size discrepancies. I have a file that is reported as 51Mb in Finder, but when uploaded to the server, the byteLength of the Buffer shows a much smaller size. Could this difference be due to the file type or other propert ...

Modifying the color of a header through clicking on a specific anchor link

My goal is to create a fixed side nav bar on my webpage with an unordered list that links down the page using anchors. In addition, I want to dynamically change the color of an h2 element based on which item in the fixed nav bar is clicked on. For instan ...

Move the scroll bar outside of the div and set it to automatically overflow

My issue involves a small div with the CSS property overflow:auto;. However, when the scroll bar appears, it covers up a significant portion of the div. One possible solution is to use overflow:scroll;, but this can result in an unsightly faded scroll bar ...

Exploring Time Scaling and Range Adjustment in D3 Barcharts

My dataset looks something like this: dateRange = [ { date: 2017-03-23, value: 10 }, { date: 2017-03-25, value: 15 }, { date: 2017-04-01, value: 13 }, { date: 2017-04-02, value: 19 } ]; The results can be viewed here: https://embed.plnkr.co/iOBAuCZmo ...

The object's type remains a mystery

While working on implementing jwt authentication in Ionic, React with TypeScript, I faced a typescript error when trying to add a check in my App.tsx file after successful implementation. The error stated: Object is of type 'unknown' Below is ...

Having issues with Jquery and duplicating tables functionality not functioning as expected

I am facing an issue with two external jQuery files. One file allows me to clone the last row of a table, while the other is supposed to retrieve the id of a select tag based on a class assigned to it. However, the second script only works for the original ...

Tips for resolving the error "Cannot access the title property of undefined" when utilizing NextJS prerendering

I am preparing this page in advance for a specific post within my Next.js application: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from &apos ...