DMIL
DMIL

Reputation: 703

jquery: select elements except own children

I need to select elements of a certain class except children of $(this). The trick is no elements have an id attribute and the classes of parent and children elements are the same, so

<div class="onedoc">1
    <div class="onedoc">1.1
        <div class="onedoc">1.1.1</div>
    </div>
    <div class="onedoc">1.2</div>
</div>
<div class="onedoc">2</div>
<div class="onedoc">3</div>

in this example, if $(this) is 1 (the first element), I need to select elements containing 1.1.1, 2 and 3

Upvotes: 1

Views: 159

Answers (3)

moribvndvs
moribvndvs

Reputation: 42495

 $('.onedoc:not(:has(.onedoc))');

You can specify the target by doing this:

 $('.onedoc:not(:has(.onedoc))', $target); // where $target is some element you selected

http://jsfiddle.net/HackedByChinese/PqxbL/

Upvotes: 1

Jon Egerton
Jon Egerton

Reputation: 41589

You can use jquery remove(): http://api.jquery.com/remove/.

Select all the onedoc elements, then remove the child elements from the DOM using remove()

e.g.

$('.onedoc').remove($(this).children());

Edit as per comments: If you don't want to include the node itself, then remove that too:

$('.onedoc').remove($(this).children()).remove($(this));

Upvotes: 0

Anthony Grist
Anthony Grist

Reputation: 38345

Something like this should work:

$('.onedoc').not($(this).children());

DEMO

Upvotes: 4

Related Questions