0

(Javascript) I stole this very nice code from another post here.
It changes the style.backgroundColor of those div elements with .onmouseover.

<div id='idEl' class='classEl'>1</div>
<div id='idEl' class='classEl'>2</div>
<div id='idEl' class='classEl'>3</div>
<div id='idEl' class='classEl'>4</div>
<div id='idEl' class='classEl'>5</div>
<script>
  var div = document.getElementsByTagName("div");
  for(var i = 0; i < div.length; i++) {
  div[i].onmouseover = function() {
     this.style.backgroundColor = "green";
  }
</script>

This works, but instead of doing it with TagName (that would mess up all of my other dozens of div), I would like to make it work with id (if it's even possibile) or with className.
And without using the html attributes, all should be done through object properties inside the <script>.
It would be great if even the mighty addEventListener could work.

Salomanuel
  • 897
  • 10
  • 22

2 Answers2

2

just change getElementsByTagName to getElementsByClassName

here is the Working fiddle and CODE -

<div id='idEl' class='classEl'>1</div>
<div id='idEl' class='classEl'>2</div>
<div id='idEl' class='classEl'>3</div>
<div id='idEl' class='classEl'>4</div>
<div id='idEl' class='classEl'>5</div>
<script>
  var div = document.getElementsByClassName("classEl");
  for(var i = 0; i < div.length; i++) {
  div[i].onmouseover = function() {
     this.style.backgroundColor = "green";
     }
  }

</script>

Note - You are also missing a closing bracket } which i put in above code and you sre using same id's for every div which is incorrect because id's should be unique.

Manoj Salvi
  • 2,639
  • 1
  • 17
  • 21
1

To get elements by css class you can use the getElementsByClassName function

document.getElementsByClassName("classEl");

Note that it's better then using 'id' in your case because html dose not allow multiple same ids on the same document.

To get element (not elements) you can:

document.getElementById("my_unique_id");

You can see working example - here

Adi Darachi
  • 2,137
  • 1
  • 16
  • 29