Reputation: 7599
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
Upvotes: 1
Views: 416
Reputation: 106412
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');
}
Upvotes: 2
Reputation: 769
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);
}
Upvotes: 0
Reputation: 54615
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>
Upvotes: 1
Reputation: 872
just use $("#main > div.item"). the ">" selector makes sure that what you put after that are children of what comes before.
Upvotes: 1
Reputation: 490637
$('#main > div.item')
Select the #main div, then select only direct child div elements with a class of item.
Upvotes: 1