ug_
ug_

Reputation: 11440

Select children where not within container jquery

This would seem like an easy problem but I am having some trouble figuring this one out. The example given is a SSCCE and I have a larger problem that this attempts to solve. In order for this to work the query must NOT contain any immediate child selectors (>) due to the dom tree being a bit more complex than this example.

My goal here is to select all children whom aren't underneath a parent who contains a class. In this example I am trying to select the 2 div containers hello and world but not foo and bar.

Here is a plunker that has the code in it for your convience. http://plnkr.co/edit/4zsKAFts5X7X2kLADj2V?p=preview


Using this HTML:

<div id="root" class="parent">
  <div>
    <div class="child">hello</div>
    <div class="child">world</div>
  </div>
  <div class="parent">
    <div>
      <div class="child">foo</div>
      <div class="child">bar</div>
    </div>
  </div>
</div>

And this Javascript:

var root = $('#root');
$(':not(.parent) .child', root).css('font-weight', 'bold');

I am seeing this result:

hello

world

foo

bar

But what I would like to get is

hello

world

foo

bar


To reiterate I want to get all elements with class child who dont have a parent with class parent starting from a given node (in this example #root).

Upvotes: 1

Views: 567

Answers (5)

guest271314
guest271314

Reputation: 1

    $("#root .child:not(#root .parent * .child)")
    .css("font-weight", "bold")

jsfiddle http://jsfiddle.net/guest271314/UJJXU/

Upvotes: 0

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

JSFiddle: http://jsfiddle.net/TrueBlueAussie/78G6N/3/

var root = $('#root');
$('#root').find('.child').filter(function(){
    return $(this).closest('.parent').is(root);
}).css('font-weight', 'bold');

I also improved j08691's solution so that it uses the root node supplied, rather than duplicating the selector (which is not portable):

http://jsfiddle.net/TrueBlueAussie/78G6N/4/

var root = $('#root');
$('.child',  root).not(root.find(".parent .child")).css('font-weight', 'bold');

Upvotes: 1

MonkeyZeus
MonkeyZeus

Reputation: 20737

It might not be pretty but here you go:

$('#root').find('.child').filter(function(){
    if($(this).parents('.parent').first().attr('id') === 'root'){
        return 1;
    }
    else{
        return 0;
    }
}).css('font-weight', 'bold');

http://jsfiddle.net/PDZL8/

Upvotes: 1

j08691
j08691

Reputation: 207861

var root = $('#root');
$('.child',  root).not($("#root .parent .child")).css('font-weight', 'bold');

jsFiddle example

Upvotes: 3

Karl-Andr&#233; Gagnon
Karl-Andr&#233; Gagnon

Reputation: 33870

You can use this :

$('#root').find('.child').filter(function(){
    return $(this).parents('.parent').length <= 1;
}).css('font-weight', 'bold');

It check the number of parent the div has and if it is lower or equal than 1, it return the child.

Fiddle : http://jsfiddle.net/akwPb/

Upvotes: 0

Related Questions