views:

93

answers:

5

hi i'm having this markup:

<div id="main">
     <div nam="item">1</div>
     <div nam="item">2</div>

     <div>
           <div nam="item">3</div>
           <div nam="item">4</div>
           <div nam="item">5</div>
     </div>

     <div nam="item">6</div>
     <div nam="item">7</div>
</div>

i'm now selecting only the direct child divs by using this method:

var divs = $("#main > [nam]"

my question - i want to do this inside a function where i only pass the parent div, how would i need to change the selector?

function get_rootChildren(div)
{
      return($("* > [nam]",div));
}

^ this is bogus but i think u know what i mean - how could this be done? thx, fuxi

+1  A: 
$('#main > div.item')

Select the #main div, then select only direct child div elements with a class of item.

alex
+1  A: 

Perhaps:

$("#main > div.item")

From jQuery Selector Docs

parent > child

Matches all child elements specified by "child" of elements specified by "parent".

To answer part two - I would use .children() something like this:

function get_rootChildren(div) {
   $(div).children('div.item');
}
gnarf
It's also worth noting, for future-reference, that this type of selector is part of CSS 2; albeit in the unlucky part of CSS 2 that IE 6 chose not to implement. Luckily, jQuery handles it for you.
JasonWyatt
This will also select elements which aren't divs
jitter
Updated to force `div` for you jitter, also updated to include an alternate answer to part two.
gnarf
+1  A: 

just use $("#main > div.item"). the ">" selector makes sure that what you put after that are children of what comes before.

lamelas
+1  A: 

Modified to fit new question

//returns direct children of parent which are divs and have an attribute named name with value item
function get_rootChildren(parent){
  return $(" > div[nam='item']", parent);
}


If your structure code is really going to look like the sample you provided then the following will do it.

$('#main > div.item')

The following is also able to handle more complex structures

$("#main > div.item:not(:has(>div))").each(function(index,item){
    alert($(item).text());
});

e.g. on the following my second selector would still only deliver 1,2,6,7 while the first would deliver 1,2,3,5,6,7

<div id=main>
  <div class="item">1</div>
  <div class="item">2</div>
  <div class="item">
    <div class="item">3</div>
  </div>
  <div>
    <div>4</div>
  </div> 
  <div class="item">
    <div>5</div>
  </div> 
  <div class="item">6</div>
  <div class="item">7</div>
</div>
jitter
A: 

If you are passing the id of the parent as a string, you could build the expression before you call it:

function get_rootChildren(divId) {
    var expr = "#" + divId + " > [nam]"; // creates expression for jQuery call
    return $(expr);
}
Ken Earley