Assign onmouseover events to Dyanmically genereated list

1.4k views Asked by At

I'm looking to create a function in JavaScript to manipulate a list of items. The list is being generated by a CMS and I can only affect it with JavaScript.

Let's assume the list is as follow:

<ul id="someUniqueID"> 
  <li class="genericClass" id="uniqueGeneratedID"><a href="link1.htm">Link</a></li>
  <li class="genericClass" id="uniqueGeneratedID2"><a href="link2.htm">Link 2</a></li> 
  <li class="genericClass" id="uniqueGeneratedID3"><a href="link3.htm">So on and so forth</a></li> 
</ul> 

Now, I know that JavaScript offers the ability to use

document.getElementById('uniqueGeneratedID').onmouseover = doSomething(); 
function doSomething(){ //code here } 

What'd I'd like to do is instead grab all of those li's and assign an onmouseover function to each of them without specifically identifying each li element.

I've been doing it like this,

var x = document.getElementsByTagName('li'); 
var changeId = new Array(); 
for (var i = 0; i < x.length; i++)
{
    var j = 0; 
    changeId[j] = x[i].id;
    j++; 
} 
function mouseOver() {
for(var y = 0; i < x.length;  y++){
        document.getElementsById(changeId[y]).onmouseover = test(changeId[y]); 
    }    
}
function test(storeContent){
    document.getElementsById('storeContent').innerHTML = 'printing' + testId; 
}
mouseOver();

The problem of course is that this doesn't actually generate any kind of onmouse over event for the ID's. Is there a way to dynamically assign all of the li's an onmouseover event without going through generating a

document.getElementsById('uniqueGeneratedID').onmouseover = doEvent(); 
document.getElementsById('uniqueGeneratedID2').onmouseover = doEvent(); 

etc.?

Thanks for any help or suggestions.

1

There are 1 answers

0
Jeremy On BEST ANSWER

A quick and dirty way would be to grab the parent <ul> and loop through its children:

var ul = document.getElementById("someUniqueID"),
    lis = ul.getElementsByTagName("li");

for (var i = 0, l = lis.length; i < l; i++) {
    lis[i].onmouseover = function() {
        this.style.color = "red";
    };
}

Example: http://jsfiddle.net/rttXQ/