0

I was writing a small javascript function if I click in the element where class name is clickme it will change the html of demo class.but it is not working.it is working if I change it to an id what is the reason of it.

<p id="clickme">Click Me</p>

<p class="demo"></p>

<script>
document.getElementsByClassName("clickme").addEventListener("click", 
function(){
document.getElementsByClassName("demo").innerHTML = "Hello World";
});
</script>
Cœur
  • 37,241
  • 25
  • 195
  • 267
user1722366
  • 71
  • 1
  • 1
  • 5
  • 3
    [getElementsByClassName](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementsByClassName) "Returns an array-like object of all child elements which have all of the given class names" –  Aug 08 '18 at 17:51

2 Answers2

1

document.getElementsByClassName returns an array of matches. So you need to iterate through your elements

<script>
var elems = document.getElementsByClassName("clickme");
for (var i=0; i < elems.length; i++) {
  elems[i].addEventListener("click", function(){
      //iterate over this too
      //document.getElementsByClassName("demo").innerHTML = "Hello World";
  });
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
-1

it is:

<!DOCTYPE html>
<html>
<body>

<p>The addEventListener() method is not supported Internet Explorer 8 and earlier versions.</p>

<p>This example demonstrates a solution that will work for all browsers.</p>

<button id="myBtn" class="btn">Try it</button>

<script>
var x = document.getElementsByClassName('btn')[0];
if (x.addEventListener) {
x.addEventListener("click", myFunction);
} else if (x.attachEvent) {
x.attachEvent("onclick", myFunction);
}

function myFunction() {
alert("Hello World!");
}
</script>

</body>
</html>