element.className not working - FIXED

element.className not working - FIXED
0.0 0

#1

Hi everyone.
I’m studying events from a book (Beginning Javascript 5th edition) and at one point I have to do an exercise which involves text changing class when mouse is moved on it.
Problem is element.className appears to not work and I’m not sure why.
Would you mind checking my code and seeing if you can figure out what’s going on?

Thanks.

<!DOCTYPE html>

<html lang="en">
<head>
  <title>Chapter 10: Example 8</title>
  <style>
     .underline {
       color: red;
       text-decoration: underline;
     }
  </style>

</head>
<body>
   <p>This is paragraph 1.</p>
   <p>This is paragraph 2.</p>
   <p>This is paragraph 3.</p>

   <script>
     function handleEvent(e) {
        var target = e.target;
        var type = e.type;

        if (target.tagName == "p") {
          if (type == "mouseover") {
            target.className = "underline";
          } else if (type == "mouseout") {
            target.className = "";
          }
        }
        if (type == "click") {
          alert("You clicked the mouse button at the X:"
                 + e.clientX + " and Y:" + e.clientY + " coordinates");
        }
     }

     document.addEventListener("mouseover", handleEvent);
     document.addEventListener("mouseout", handleEvent);
     document.addEventListener("click", handleEvent);
   </script>
</body>
</html>

EDIT: I fixed it. It was a silly mistake (wrote “p” instead of “P” in the first if statement). I don’t know how to delete a post!


#2

You need to specify an element for the mouseover, mouseout, and click. Read about querySelector and getElementsByClassName which you could use with your p elements.


#3

it was actually just a minor error. I wrote tagName == “p”, and it was supposed to be P, in uppercase. I didn’t know tagname was supposed to be in uppercase and I still don’t know if this is always the case, but it worked.