MStodd MStodd - 3 months ago 10
jQuery Question

jQuery not child of class

If I have:

<div class="wrapper">
<div>
<div class="list">
</div>
</div>
<div class="wrapper">
<div class="list">
</div>
</div>
<div class="list">
</div>
</div>


When I have a jQuery instance of a 'wrapper' div, how can I find things in that div, but not in any child 'wrapper' div?

I want to
wrapper.find('.list')
and get the first and third lists, but not the second.
wrapper.find('.list').not('.wrapper .wrapper *')
seems to work, but not sure if there's something better.

Answer

I think you might be looking for something like this:

var $target = $(".wrapper .list").filter(function(){
  return $(this).parents(".wrapper").length === 1;
});

$target.css("background-color", "coral");
div{
  min-height: 10px;
  min-width: 10px;
  padding: 10px;
  border: solid 1px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="wrapper">
    <div>
        <div class="list"></div>
    </div>
    <div class="wrapper">
        <div class="list"></div>
    </div>
    <div class="list"></div>
</div>