2

Here's a quick one. I'm trying to get better at writing selectors for jquery because I seem to be relying on loops far too much in order to get things done.

In this particular example, I want to add the "Absolute" class too all of the divs that have the ganttview-block-container class except the last one in the parent ganntview-blocks div.

HTML:

<div class='ganttview-blocks'>    
 <div class='ganttview-block-container'></div>
 <div class='ganttview-block-container'></div>
 <div class='ganttview-block-container'></div>    
</div>

<div class='ganttview-blocks'>    
 <div class='ganttview-block-container'></div>
 <div class='ganttview-block-container'></div>
 <div class='ganttview-block-container'></div> 
</div>

Javascript:

$("div.ganttview-block-container").addClass("Absolute").addClass("Opacity");

$($("div.ganttview-blocks")).each(function () {
  var thisDiv = $(this);
  thisDiv.children("div.ganttview-block-container:last").removeClass("Absolute");    
});

My javascript/jquery accomplishes this goal correctly but it seems so inefficient. I'm confident there's a more elegant way of getting this done... perhaps even in 1 line.

Can anyone help? Thanks!

RoboKozo
  • 4,981
  • 5
  • 51
  • 79

2 Answers2

5

I think you need :not with :last-child:

$('.ganttview-block-container')
  .addClass('Opacity')
  .filter(':not(:last-child)')
    .addClass('Absolute');
lonesomeday
  • 233,373
  • 50
  • 316
  • 318
0

why not just do

$("div.ganttview-blocks div.ganttview-block-container:last").each( ... )

That should get you the elements your after.

Dave G
  • 9,639
  • 36
  • 41