MStodd
MStodd

Reputation: 4746

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.

Upvotes: 1

Views: 2458

Answers (3)

JonSG
JonSG

Reputation: 13067

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>

Upvotes: 4

Marcelo Borges
Marcelo Borges

Reputation: 138

I guess something like this could solve your problem:

$( ".wrapper:first" ).children( ".list" )

Where $( ".wrapper:first" ) would get only the first appearance of .wrapper, and children( ".list" ) would get only its children

I hope that's what you are looking for

Upvotes: 0

Kewin Dousse
Kewin Dousse

Reputation: 4027

Use selector :only-child.

For your example :

$('.wrapper:only-child').children('.list');

Will only return all the first level '.list' divs.

Upvotes: 0

Related Questions