0

Im fairly new to JavaScript and i am attempting to make an onmouseover event change the color of an h1 tag to red, and changes it back to black onmouseout. I know there are much easier/simpler ways to achieve this with css, such as simply using hover styling, but i just want to understand WHY this isn't working in the first place when the syntax seems to be alright?

<h1 class="demo">Mouse over me</h1>


<script>
  document.getElementsByClassName("demo").onmouseover = function() {mouseOver()};
  document.getElementsByClassName("demo").onmouseout = function() {mouseOut()};

  function mouseOver() {
    document.getElementsByClassName("demo")[0].style.color = "red";
  }

  function mouseOut() {
    document.getElementsByClassName("demo")[0].style.color = "black";
  }
</script>
Mamun
  • 66,969
  • 9
  • 47
  • 59
BernieBro
  • 49
  • 1
  • 5

1 Answers1

1

Class refer multiple component so add [0] index same as you mouseover function call

<h1 class="demo">Mouse over me</h1>


<script>
  document.getElementsByClassName("demo")[0].onmouseover = function() {mouseOver()};
  document.getElementsByClassName("demo")[0].onmouseout = function() {mouseOut()};

  function mouseOver() {
    document.getElementsByClassName("demo")[0].style.color = "red";
  }

  function mouseOut() {
    document.getElementsByClassName("demo")[0].style.color = "black";
  }
</script>
prasanth
  • 22,145
  • 4
  • 29
  • 53