Applying an onClick array to an element in a for loop

I am trying to apply the onClick event to an array of elements in a document, for example:

for (var i = 0; i < myElems.length; i++)
     myElems[i].onClick = "someFunction(this)";

The code is placed inside the init () function for the onLoad event of the body tag. I notice that when loading a document the functions will not work.

I noticed that if I add alert () to tell me if there is a problem:

for (var i = 0; i < myElems.length; i++)
     myElems[i].onClick = "alert('It worked!')";

The document will load and execute a warning for all the elements, regardless of whether I really clicked on the element.

What am I doing wrong?

+5
source share
2 answers

The name of the property onclick.

onclick, although it is valid HTML, does not exist in JS as it is case sensitive.

You also need to assign him a link to a function or expression, as David answered (+1).

Fiddle

+2

'onclick' :

for (var i = 0; i < myElems.length; i++)
     myElems[i].onclick = function() { someFunction(this);};

"alert" ( ). , , - , .

+3

All Articles