Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting root element in jquery

I need to be able to select the root element from a fragment without knowing the node types, class, id or hierachy.

<div id="0">
    <div id="0a">
        <div id="a01"></div>
    </div>
    <div id="0b">
    </div>
    <div id="0c">
    </div>
</div>

I want to be able to do something like $(':root') and have 0 selected in the example above.

Better still I would prefer $(':level(0)') which would mean the same as above, $(':level(1)') would select 0a, 0b and 0c and $(':level(1)>div') would select a01.

Any ideas on how to do it neatly?

like image 762
Sqoo Avatar asked Oct 30 '09 14:10

Sqoo


1 Answers

OK, so what you need to do is the following (presuming that you are using the sample you've got), if you want to find the top level node using jquery is the following:

 $('*:not(* *)');  

What you are literally asking for here is for all nodes that are not children of other nodes. The problem is that for a html document, this will always give you only the html element, which isn't particularly useful. So, if you want to find the top level element within the body of a html document, you'd use something a lot simpler:

 $('body > *');

if you then wanted the second level, you'd just go

 $('body > * > *');

But, presuming you have some sort of arbitrary document structure (like the foo one you mention), what you can do is use the first example to find the first level:

 $('*:not(* *)');

and then for the second level

 $('*:not(* *)').find('> *');

and for the third level

 $('*:not(* *)').find('> * > *');

and so on and so forth. If you're looking for a root div element (presuming that your sample is like the question), you can do this:

 $('div:not(div div)');

and so on, replacing * with div. Not really sure why you'd want to do this, but it will work. The problem is the question doesn't really provide enough context for us to give you a better alternative.

like image 59
Deeksy Avatar answered Sep 22 '22 23:09

Deeksy