PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 15, 2022

[FIXED] How to Use Element ID to getElementsByClassName?

 October 15, 2022     dom, dom-events, javascript     No comments   

Issue

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?


Solution

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";


Answered By - Onur Topal
Answer Checked By - Robin (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing