parap
parap

Reputation: 1985

How to Use Element ID to getElementsByClassName?

I have a script that will findElementById across multiple frames and will highlight/change the text color. The script works so that when you mouseover each word of "The quick brown fox," the word under your pointer will be red and highlighted in yellow. The same word in frame2 will be red/highlighted as well. Note that the element ids are identical to the class name(s).

<html><head><title>Test</title>
  <script>
    function hey(id)
      {document.getElementById(id).style.color = "red";
      document.getElementById(id).style.backgroundColor = "yellow";
      window.parent.frames["frame2"].document.getElementById(id).style.color = "red";
      window.parent.frames["frame2"].document.getElementById(id).style.backgroundColor = "yellow";} 
    function bye(id)
      {document.getElementById(id).style.color = "black";
      document.getElementById(id).style.backgroundColor = "white";
      window.parent.frames["frame2"].document.getElementById(id).style.color = "black";
      window.parent.frames["frame2"].document.getElementById(id).style.backgroundColor = "white";}
  </script>
</head>
<body>
  <a id="w1" class="w1 w4" onmouseover="hey(this.id)" onmouseout="bye(this.id)">The</a> 
  <a id="w2" class="w2" onmouseover="hey(this.id)" onmouseout="bye(this.id)">quick</a>
  <a id="w3" class="w3" onmouseover="hey(this.id)" onmouseout="bye(this.id)">brown</a> 
  <a id="w4" class="w1 w4" onmouseover="hey(this.id)" onmouseout="bye(this.id)">fox</a>
</body></html>

Now I want to edit this script so that it takes the id and finds elements by class. For example, when you mouseover "fox" the id="w4". I want to find "w4" in the link's class so that both "The" and "fox" will be red/highlighted whenever either is moused over. I can't figure out how to use getElementsByClassName using values from the id. Any thoughts?

Upvotes: 0

Views: 2508

Answers (1)

Onur Topal
Onur Topal

Reputation: 3061

the getElementsByClassName returns an array you have to loop over it. try the below code.

var elements = document.getElementsByClassName(id);

for(var i=0; i<elements.length; i++)
    elements[i].style.color = "red";

Upvotes: 1

Related Questions