Ridoy Dey
Ridoy Dey

Reputation: 49

How can I change the background of each element with a specific class on mouseover?

I'm trying to change the background of elements with the class "heading" on mouseover.

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 problem is that the background only changes for the first element with the class "heading". I don't know how to make this work for the other elements. How can I achieve this?

Upvotes: 0

Views: 402

Answers (2)

Client
Client

Reputation: 140

You are using document.querySelector() to get the element with the class name heading, if there's more than one element it will only get the first one. Here you need to use item instead of heading to change the elements style which you are adding mouseover event to.

Upvotes: 0

PsiKai
PsiKai

Reputation: 1978

In your code snippet you are not following the iterator variable that you set in your forEach callback function. Change that to item instead of heading and it should work.

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>

Notice that I got rid of your heading variable as it did not need to be used in my snippet.

Upvotes: 2

Related Questions