What is the best way to modify the background of individual elements by targeting a specific class when hovering over them?

Looking to dynamically change the background of elements in the "heading" class when hovered over.

const heading = document.querySelector('.heading');
const headingAll = document.querySelectorAll('.heading');
headingAll.forEach(item => {
  item.addEventListener("mouseover",()=>{
    heading.style.backgroundColor='teal';
  });
})
.heading{
  background-color: yellow;
  width: 50%;
  margin:0 auto;
  padding: 10px;
  border: 1px solid red;
  cursor: pointer;
}

.heading2,heading3{
  margin-top: 10px;
}
<h1 id='heading' class='heading heading2'>First Heading</h1>
<h2 id='heading' class='heading heading2'>Sub Heading</h2>
<h3 id='heading' class='heading heading3'>Third Heading</h3>

The issue is that only the first element with the class "heading" changes background on mouseover. How can I extend this functionality to work for all elements with the same class?

Answer №1

Your implementation in the code snippet lacks adherence to the iterator variable set in the forEach callback function. To rectify this, replace all instances of heading with item and your code should function correctly.

const headingAll = document.querySelectorAll('.heading');
headingAll.forEach(item => {
  item.addEventListener("mouseover",()=>{
    item.style.backgroundColor='teal';
  });
})
.heading{
  background-color: yellow;
  width: 50%;
  margin:0 auto;
  padding: 10px;
  border: 1px solid red;
  cursor: pointer;
}

.heading2,heading3{
  margin-top: 10px;
}
<h1 id='heading' class='heading heading2'>First Heading</h1>
<h2 id='heading' class='heading heading2'>Sub Heading</h2>
<h3 id='heading' class='heading heading3'>Third Heading</h3>

I have omitted the use of the unnecessary heading variable in my provided code snippet.

Answer №2

Instead of using document.querySelector() to retrieve the element with the class name "heading", consider utilizing the "item" method when there are multiple elements present. This will allow you to modify the style of the specific element that you are applying the mouseover event to.

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

Failure to achieve closure - even after thorough study of the concept

I have a countdown that I'm trying to get working during onload, but I'm running into issues with closures. Here is my code: Check out the fiddle here for (var o in myDates) { var myDate = myDates[o]; var iid = o; funcs[o] = function() { ...

When I attempt to send a PUT request, the req.body object appears to be empty. This issue is occurring even though I have implemented the method override middleware

I am currently facing an issue with updating a form using the put method. To ensure that my form utilizes a PUT request instead of a POST, I have implemented the method override middleware. However, upon checking the req.body through console log, it appear ...

Is there a way for a button to automatically delete its corresponding index in an array upon being clicked?

I am currently developing a multiple choice quiz where users can input their own questions and answers to create a quiz. I am facing an issue with allowing users to delete questions stored in the question bank. Here is what I have tried so far: bodyText ...

Observables in Knockout.js vanish after being bound

I'm encountering a peculiar issue with my Knockout script. Here is the viewModel: viewModel = { viewShown: function () { if (params.id !== undefined) timer = setInterval(loadVorgangsdetails, 100); else { $( ...

Error occurred while trying to create module 'app' in Angular and MEAN stack

Recently, I delved into the MEAN stack using Express, Node, Jade, and Angular. However, it seems like there's a problem with Jade that I can't quite wrap my head around. The error message I'm getting is: Uncaught Error: [$injector:modulerr] ...

In Safari, non-ascii characters are incorrectly stored in document.cookies as trash

Below is a snippet of JavaScript code that I am working with: wdata['account'] = {"value": $(input).val(), "title": "Номер карты получения"}; var r = { "ipayway": ipw_selected, "wpayway": wpw_selected, "amount_type" ...

What are some best practices for managing object-level variables in TypeScript and Vue.js?

Uncertain about the optimal approach, I am looking to create a component and leverage some object level variables. Consider the example below: import Vue from "vue" import * as paper from "paper" export default Vue.extend({ template: ` <d ...

Is there a way to display multiple images in a JSON message object?

If you're looking for a fun way to generate random dog images, then check out my DogAPI image generator! Simply enter a number between 1-50 into the form text box, hit send, and watch as it displays that amount of random dog photos. I'm almost t ...

Tips for transferring current subscription information with Stripe at the time of checkout

Currently, I offer various subscription plans on Stripe, starting from Zero. Whenever a customer signs up, I automatically create a subscription with the free plan. In the future, if a customer wants to upgrade their plan during checkout, how can I ensure ...

TaffyDB is throwing an error message indicating that TAFFY is not recognized as a function

I am currently developing a web-based game using HTML, CSS & JavaScript within Visual Studio and utilizing TaffyDB as my database. However, I have encountered an error when trying to create a database using the TAFFY function, as it keeps showing up in the ...

React-slick slider not functioning properly when using TypeScript

I encountered an issue while trying to implement a carousel/slider using the typescript version of the react-slick library in my Nextjs project. After importing the Slider component from the package, I received the following error: https://i.sstatic.net/6 ...

Ternary conditionals don't support splicing

Seeking a solution to eliminate any duplicate numbers from two arrays: function removeDuplicates(args) { var uniqueNumbers = [].concat.apply([],arguments).reduce( function(result, current) { console.log("result: " + result); console.lo ...

What is the best location for storing your front-end javascript files?

As I work on my web application using Express, I've utilized the application skeleton provided by the express-generator. To bundle my client-side assets, I've integrated webpack into my project. Now, I'm faced with a dilemma on where to st ...

Guide to setting up a lobby system with Javascript within a Django framework

I am looking to develop a lobby system where users can create rooms, other users can join the room, and the creator of the room will select 9 participants to form 2 teams of 5 players each. Once both teams are finalized, the creator will close the room wit ...

Refreshing ng-repeat dynamically with $http without reloading the page

Just a quick heads-up, I'm new to AngularJS In my AngularJS application, I am using the $http service to fetch data. Each row has an update button that needs to trigger a server-side method (the API is already returning data) to sync with a third-par ...

Adjusting the height of a DIV element to suit the window dimensions

I am facing an issue with the following HTML code: <div id="subpageHeaderImageSection"> <div id="subpageHeaderLeft"> <span id="holdImageP"></span> <!--[if lte IE 10]><img id="igm" src="theImages/sub ...

Error: The function m.easing[this.easing] is not defined

I have been working on creating anchor link scrolling and tooltip display using bootstrap, but I am encountering an issue. $(window).scroll(function(){ if ($(window).scrollTop() >= 100) { $('#header').addClass('fixed'); ...

What could be the reason for the undefined initial state in my vuex store?

I am facing an issue with vuex-typescript where the initial state is always undefined. However, it works fine when I reset the state and refresh the window. Below is my setup for a simple module: import Vue from "vue"; import Vuex from "vuex"; import { m ...

What is the minimum number of characters required to embed JavaScript using the HTML5 <script> element?

Is this the most efficient way to include external JavaScript on a page, now that the type attribute of the <script> tag can be omitted in HTML5? <script src="URL"></script> Is there a way to optimize this further, especially if a frame ...

Transferring SetState from a parent component to a child component in React Native

When working with React js, passing setState from parent components to child components is done like this. However, in React Native setABC is undefined. What is the recommended approach for achieving similar functionality in React Native? Parent.js: funct ...