1

The function that I define inside an onclick event does not work.

I don't know what I am missing. Also I should mention that I have already checked to see if JavaScript is linked to HTML correctly and it is.

https://jsfiddle.net/5sg4owpu/7/

HTML:

<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="utf-8">
    <title> Practice 1</title>
    <link href="indexStyle.css" rel="stylesheet" type="text/css">
  </head>

  <body>
    <p class="hello">Hello There!</p>

    <script src="newjavascript.js"></script>

  </body>
</html>

CSS:

.hello {
  border: 1px solid black;
  width: 100px;
  background: blue;
}

JavaScript:

var mm = document.getElementsByClassName("hello");
mm.onclick=function () {
    alert("It worked!");
};
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
Meysam
  • 33
  • 6
  • Possible duplicate of [What do querySelectorAll, getElementsByClassName and other getElementsBy\* methods return?](http://stackoverflow.com/questions/10693845/what-do-queryselectorall-getelementsbyclassname-and-other-getelementsby-method) – Sebastian Simon Feb 03 '17 at 01:49

3 Answers3

1

It's not working as expected because the method getElementsByClassName returns a collection of elements. This means that you would need to access a specific element within that collection in order to add the event listener. You were attempting to add an event listener to the entire collection, which clearly wasn't working.

For instance, you could add the event listener to the first element in the collection:

Updated Example

var m1 = document.getElementsByClassName("hello");

m1[0].onclick = function() {
  alert("It worked!");
};

However, it would be better just to use a method such as document.querySelector in order to select the desired element. In this case, the method querySelector will only return a single element.

Updated Example

var m1 = document.querySelector(".hello");

m1.addEventListener('click', function () {
  alert("It worked!");
});

You may also want to check to make sure the element exists before applying the event listener, otherwise an error will be thrown:

var m1 = document.querySelector(".hello");

if (m1) {
  m1.addEventListener('click', function() {
    alert("It worked!");
  });
}
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304
1

document.getElementsByClassName() returns an array, you will need to access the first element of the array so that you can then define its onclick function:

var mm = document.getElementsByClassName("hello")[0];
mm.onclick = function() {
  alert("It worked!");
};
hackerrdave
  • 6,486
  • 1
  • 25
  • 29
0

getElementsByClassName returns an Array and an Array does not have an onclick function. You need to access the element and set the function callback on it.

var mm=document.getElementsByClassName("hello");
mm[0].onclick=function(){
    alert("It worked!");
};
Teddy Sterne
  • 13,774
  • 2
  • 46
  • 51