lowkey
lowkey

Reputation: 321

mootools "this" in each?

Probably misunderstanding something simple, but i can't seem to get this to work.

I want to: go trough each img element in "wrapper", and strip all html from the title attribute (with stripTags() from mootools more). I get the error:

"this.get is not a function"

here is the code:

$('wrapper').getElements('img').each(function() {

    var oldAlt = this.get('title').stripTags();
    this.setProperty('alt', oldAlt);

});

Thanks in advance

Upvotes: 1

Views: 4675

Answers (2)

Jeremy
Jeremy

Reputation: 4930

The other option is to bind the this variable

$('wrapper').getElements('img').each(function() {

    var oldAlt = this.get('title').stripTags();
    this.setProperty('alt', oldAlt);

}).bind(this);

The extra .bind(this) basically means, in the scope inside the each function, the variable this is bound to whatever value is refers to outside. (like passing the variable into the scope). If you have need to access the normal this pointer as well, as the outside reference, you should go with an option such as @Chetan's answer

Upvotes: -2

Dimitar Christoff
Dimitar Christoff

Reputation: 26165

$('wrapper').getElements('img').each(function(el) {
    var oldAlt = el.get('title').stripTags();
    el.setProperty('alt', oldAlt);

});

this does not refer to the looping element -- the first argument to the .each callback function is element passed, the second is index (opposite to jquery where index is first).

Upvotes: 6

Related Questions