An Original Alias
An Original Alias

Reputation: 203

How to apply a method to an entire object literal?

How do you apply a method to all properties of an object literal?

For Example:

var ObjL = {
    x: $("someSelector > .x"),
    y: $("someSelector > .y"),
    otherx: $("someOtherSelector > .x"),
    othery: $("someOtherSelector > .y"),
    ...
    ...
    ...
    }
// <---something like ObjL.css("background-color","red") would go here

Would you just use ObjL.someMethod()?

Could you do this with an array?

Upvotes: 0

Views: 46

Answers (3)

Luis Masuelli
Luis Masuelli

Reputation: 12333

If I understand you correctly, you want to apply a method aMethod to an element? The best solution IMHO is a foreach loop:

$.each($obj, function(prop, value) {
    //call a method here, being the same on value or this.
    value.css(blablabla, blablabla);
});

(deliberately i did not use the for loop since 1. u're using jquery and it's shorter, and 2. it has many problems regarding the owned or inherited-by-proto properties).

EDIT: yes, you can use a $.each loop as well for arrays. an alternative is using a regular for-counter loop (for(initial;condition;increment){ code }), since using for(in) loops in arrays lead to unexpected results.

Upvotes: 2

Sebastian G. Marinescu
Sebastian G. Marinescu

Reputation: 2394

You could iterate over the object:

for (var key in ObjL) {
  if (ObjL.hasOwnProperty(key)) {
    ObjL[key].css( /* do your thang */ );
  }
}

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68400

This should do the trick

$.each(ObjL, function() {
    this.css("background-color","red");
})

Upvotes: 1

Related Questions