Everyone is suggesting some framework, but I’d like to know how it can be done in native JavaScript. I’ve tried this code and some other things, no effect. Seems that I’m unaware of some basic underlying concept. Any help would be appreciated.
window.onload = function() {
var trCurrent
var main = document.getElementById('main');
var tr = main.getElementsByTagName('tr');
function hl() {
trCurrent.setAttribute('class', 'highlight');
};
for (var x = 0; x < tr.lenght; x++) {
trCurrent = tr[x];
trCurrent.addEventListener ('mousedown', hl, false);
}
};
trCurrenttothisat yourfunction h1, becaysetrCurrentpoints to the last defined TR element (trCurrent = tr[x]for a highx)..lengthinstead of.lenght.Final code:
If you want to use an variable which is subject to change during a loop, it’s required to wrap the body in an (anonymous) function: