Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 259
foret Avatar asked Sep 26 '26 12:09

foret


1 Answers

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);
});
like image 76
kennytm Avatar answered Sep 29 '26 03:09

kennytm