Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery : Select last visible direct child

Tags:

jquery

<div class="menu-items-wrapper" style="width: 547px;">
   <div class="one" style="height: 134px;">
   <div class="two" style="display:none;height: 134px;">
   <div class="other" style="height: 134px;">
   <div class="new" style="display: none; height: 134px;"></div>
</div>

I wish to get the last visible direct child from the html above. Please note that every child div has even more html in it so thats why I want the direct child.

What I have at the moment

  jQuery(".menu-items-wrapper > div").find(":visible:last-child").css("border-right","0px");

or

  jQuery(".menu-items-wrapper > div").find(":visible:last").css("border-right","0px");

But I cannot get the last direct child to have no border. Can anyone help

forgot to mention that i have that div like 12 times in the page and want to apply it to all occurences. at the moment its only working on the last item

like image 289
BoqBoq Avatar asked Sep 03 '12 12:09

BoqBoq


1 Answers

.find() looks for children within the set of elements given, which does not yield any elements here, because the set it is executed on is the lowest level of elements in the DOM.

You need to apply :visible:last immediately to the div selector:

$(".menu-items-wrapper > div:visible:last").css("border-right","0px");​

Demo

For .find() you'd have to run it on the parent node:

$(".menu-items-wrapper").find("div:visible:last")

or just

$(".menu-items-wrapper").find(":visible:last")

Edit

To account for your addition in comments. In a scenario where there are several menu-items-wrapper elements, :last cannot be used in this manner, as it always selects the last element in the set. On the other hand :last-child would have worked if you always wanted the last element in each container, but this is of course not the case since the last child might not be the last visible child.

For that scenario, you'd have to iterate through the containers:

$(".menu-items-wrapper").each(function() {
    $('div:visible:last', this).css("border-right","0px");
});

Demo

like image 163
David Hedlund Avatar answered Oct 06 '22 22:10

David Hedlund