开发者

Selecting the last child elements of a div without looping

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("O开发者_StackOverflow社区pacity");

$($("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!


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

$('.ganttview-block-container')
  .addClass('Opacity')
  .filter(':not(:last-child)')
    .addClass('Absolute');


why not just do

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

That should get you the elements your after.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜