I want to use oneEventListener for all the element which has same class in the page . But It is just work for first one element.How can I achieve?

This is the code here just perform for first element which has .heading class.How can I achieve this? Please help me.

here is the code pen link to view this directly

<!DOCTYPE html>
<html>
  <head>
    <title>New work</title>
  </head>
  <body>
    <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>
    
  </body>
</html>

    .heading{
      background-color: yellow;
      width: 50%;
      margin:0 auto;
      padding: 10px;
      border: 1px solid red;
      cursor: pointer;
    }


    .heading2,heading3{
      margin-top: 10px;
    }

    const heading = document.querySelector('.heading');
    heading.addEventListener("mouseover",()=>{
                             heading.style.backgroundColor='teal';
                             });

Hi @rkprite09 :wave:

I see in your updated pen that you found out about querySelectorAll(). You now just need to change heading.style.backgroundColor='teal'; into item.style.backgroundColor='teal'; to change the style of each looped element.

Happy coding!
Michael

1 Like