Search code examples
javascriptprototypejsthiseach

'this' inside each function in Prototype JS


I'm trying to find a div element with example selector that also has active selector as denoted in the code.

With Prototype JS this returns windows.object rather than an individual div itself.

How do I make this to refer to each div element so that I can play with it?

$$('.example').each(function() {
    if(this.hasClassName('active')) {
        this.previous().setStyle({border:'1px solid #999'})
    }
});

Solution

  • http://api.prototypejs.org/language/Enumerable/prototype/each/

    To access the element, you don't need change the context (this) of the iterator function. The iterator function receives the item as the first argument. You just need to name the argument.

    $$('.example').each(function(div) {
        if(div.hasClassName('active')) {
            div.previous().setStyle({border:'1px solid #999'})
        }
    });
    

    Also, you can remove the conditional by updating the CSS selector passed into $$:

    $$('.example.active').each(function(activeDiv) {
        activeDiv.previous().setStyle({border:'1px solid #999'})
    });
    

    If you are interested in controlling the value of this inside of a function, check out call, apply, and bind.