Salomanuel
Salomanuel

Reputation: 955

modifying the style of multiple elements via javascript's object properties

(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.

Upvotes: 0

Views: 138

Answers (2)

Manoj Salvi
Manoj Salvi

Reputation: 2749

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.

Upvotes: 2

Adi Darachi
Adi Darachi

Reputation: 2175

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

Upvotes: 1

Related Questions