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

What is the best way to align text in the center of a div?

I just created this dropdown menu, but I am encountering an issue. Whenever I resize the div or h4 element, the text ends up at the top. Even after trying to solve it with text-align: center;, the problem persists. Here is a visual representation of what ...

Encountering difficulties while using JavaScript to complete a form due to issues with loading the DOM

Currently, I am attempting to automate the completion of a multi-page form using JavaScript. Below is the script that I am utilizing: // Page 1 document.getElementById("NextButton").click(); // Page 2 completion(document.getElementById("Rec ...

What is the reason Node.js only prints one item at a time?

Currently, I am using node.js to extract items from a text file. Right now, the code prints out the items in the terminal, but I want it to be able to accept multiple parameters and print each of them individually instead of just the last one. // Checki ...

Using PHP and Bootstrap to input data inside a modal

I am working on a page that has a form located here: https://jsfiddle.net/5tzg8kzm/9/ <body> <h1>&nbsp;</h1> <!-- Page Content --> <div class="container"> <!-- Trigger the modal with a button --> ...

Encountering issues with fs.writeFile function in a freshly set up Vue project

After initializing a new Vue project with vue cli, I encountered an error when attempting to write files in the main.js file. Below is the code snippet that caused the issue: const fs = require('fs'); // Data to be written to the file. let dat ...

What is the process for using the CLI to downgrade an NPM package to a previous minor version by utilizing the tilde version tag?

I currently have Typescript version ^3.7.4 installed as a devDependency in my project's package.json: { "name": "my-awesome-package", "version": "1.0.0", "devDependencies": { "typescript": "^3.7.4" } } My goal is to downgrade Typescript ...

Are HTML's Regular Expressions the Equivalent of JavaScript's Regular Expressions?

I have been trying to utilize the pattern="" attribute in HTML to implement regex, but unfortunately, I am unable to locate a comprehensive list of HTML regex parameters. This has led me to ponder whether the syntax for regex in HTML is similar to JavaSc ...

Dividing an array of characters within an ng-repeat and assigning each character to its individual input tag

Hello, I'm currently learning Angular and I have a unique challenge. I want to take the names in a table and break each name into individual <input> tags, so that when a user clicks on a letter, only that letter is selected in the input tag. For ...

Exploring the functionalities of the useState object with mapping techniques

While attempting to convert my class-based component to a functional style, I encountered the following code: const [foo, setFoo] = useState(null); const [roomList, setRoomList] = useState([]); useEffect(() => { setRoomList(props.onFetchRooms(props.to ...

The bootstrap switch button remains in a neutral grey color

Ordinary: Initially clicked: Click again: After the second click, it remains grey and only reverts on a different action like mouse click or selection. Is there a way to make it go back to its original state when unselected? ...

What is the best method for scrolling down a JavaScript table using Selenium in Python?

My dynamic table is created using JavaScript. When the page loads, only the first elements are visible in the source code. This means that when I try to scrape values from the table, only the initial parts are retrieved. Before scraping, I need to scroll ...

Switch up the picture when you press on it

I have a task involving a table where I want to switch out an image in the <td> when it is clicked, using a URL that I specify beforehand. The URL of the image will be provided when clicking on a link within the page. For example: index.html?type=d ...

What is the best way to showcase a div on top of all other elements in an HTML page?

As a newcomer to html and css, I have successfully created a div that contains city names. The issue I am currently facing is when I click on a button to display the div, it gets hidden behind the next section of my page. Take a look at the image below for ...

Refreshing a <div> element in Django, yet there is no visible update

As I utilize a barcode scanner to add objects to my array list, the data is populated after each scan depending on the scanning speed of the user. To exhibit this data, I have designed a dedicated page. My intention is to avoid refreshing the entire page b ...

best way to retrieve state from redux-toolkit (excluding initial state) in a Next.js environment

I am attempting to access the state of redux-toolkit in Next.js's getStaticProps (After saving the accessToken in the store, I need to access the store from getstaticprops for the API it requires) Here's what I have tried: export default functi ...

Tips on navigating an array to conceal specific items

In my HTML form, there is a functionality where users can click on a plus sign to reveal a list of items, and clicking on a minus sign will hide those items. The code structure is as follows: <div repeat.for="categoryGrouping of categoryDepartm ...

Navigating to JSON input in Express correctly

I have successfully created a basic Express-based API to serve JSON data, but now I want to enhance its functionality. The JSON file follows this structure: (some sections are excluded) [{ "ID": "1", "NAME": "George Washington", "PAGE": "http://en.w ...

Generating exportable dynamic code in Javascript

Any assistance or links to similar inquiries would be greatly welcomed as I have conducted some research but am uncertain about the best approach to take in this situation. I find it difficult to articulate exactly what I need, so I have created a visual ...

Using PHP to extract all occurrences of window.location from an HTML document using regex

Is there a way to extract all the window.location instances in PHP? I have a list of URLs that I am fetching using cURL, saving the HTML content as a string, and now I need to identify and display all the occurrences of window.location separately. I atte ...

Unable to modify the active property of the specified object as it is read-only

Presented here is the interface: export interface ProductCommand extends ProductDetailsCommand { } This is the ProductDetailsCommand interface: export interface ProductDetailsCommand { id: string; active: boolean; archive: boolean; title: ...