1

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);
    }
};
0

1 Answer 1

1
  • You have to change trCurrent to this at your function h1, becayse trCurrent points to the last defined TR element (trCurrent = tr[x] for a high x).
  • Use .length instead of .lenght.

Final code:

window.onload = function() {
    var main = document.getElementById('main');
    var tr = main.getElementsByTagName('tr');
    function hl() {
        this.setAttribute('class', 'highlight');
    };
    for (var x = 0; x < tr.length; x++) { 
        tr[x].addEventListener ('mousedown', hl, false);
    }
};

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:

window.onload = function() {
    var main = document.getElementById('main');
    var tr = main.getElementsByTagName('tr');
    for (var x = 0; x < tr.length; x++) {

        (function(trCurrent){ //Anonymous wrapper, first argument: `trCurrent`
            function hl() {
                trCurrent.setAttribute('class', 'highlight');
            };
            trCurrent.addEventListener ('mousedown', hl, false);
        })(tr[x]); //Passing a reference to `tr[x]`
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot, I didn't expected such a thorough answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.