foret
foret

Reputation: 728

jQuery class selector and 'this' reference

Here is a problem: i need to select elements on page by css class, and then set their width = parentElement.width - 1.
So code looks like this: $j('.innerCellElement').width(this.parentElement.clientWidth - 1);
When i say this i mean current element of selector. However, is not interpreted how i want. I can do loops here but i want to know if there is an elegant way of solving this problem.

Upvotes: 3

Views: 4940

Answers (1)

kennytm
kennytm

Reputation: 523304

If you're using jQuery ≥1.4.1, the .width() method can take a function as input:

$('.innerCellElement').width(function(){ return this.parentElement.clientWidth - 1; });

otherwise, loop over the collection.

$('.innerCellElement').each(function(){
  $(this).width(this.parentElement.clientWidth - 1);
});

Upvotes: 2

Related Questions