javascript - Assigning events to elements from getElementsByClassName -


javascript:

var myarr = document.getelementsbyclassname('contitm');  for(i=0;i<myarr.length;i++){     myarr[i].onmouseover = function(){         document.getelementbyid(myarr[i].id + 'mnu').style.display = "inline";     } } 

html:

<ul class="contmnu">     <li>         <a href="#" id="reqacct" class="contitm">accounts & access</a>         <ul id="reqacctmnu" class="subcontmnu" style="background-color:#cdcdcd">             <li><a href="#" class="tab">sub1</a></li>             <li><a href="#" class="tab">sub2</a></li>         </ul>     </li> </ul> 

what want assign function take in id of href , add "mnu" target id of ul below.

if writing inside of each element how display want dynamically added items classname

<a href="#" id="reqacct" class="contitm" onmouseover="showmnu(this.id)">accounts & access</a> 

you have problem famous "i" in loop equal myarr.length when method called. below 1 way around problem.

var myarr = document.getelementsbyclassname('contitm');  for(i=0;i<myarr.length;i++){     (function (elem) {         elem.onmouseover = function(){             document.getelementbyid(elem.id + 'mnu').style.display = "inline";         };     })(myarr[i]); } 

without reference elem, can use this.id inside

for(i=0;i<myarr.length;i++){     myarr[i].onmouseover = function(){         document.getelementbyid(this.id + 'mnu').style.display = "inline";     }; } 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -