Reputation: 4448
I want to select all the "input"-children of the "div"-children of my "mainDiv". I tried it with 'div input:first-child' as you can see below and as I found it on http://api.jquery.com/first-child-selector/. But it doesn't work. If I use only 'div' as filter it works fine. So what is my mistake? Or how to get to all the "input"-children in an easy way?
var data = ['name1', 'name2'];
var mainDiv = $('<div>');
for (var i = 0; i < data.length; i++)
{
var div = $('<div>').appendTo(mainDiv);
$('<input type="checkbox">').appendTo(div);
div.append(' ' + data[i]);
}
mainDiv.children('div input:first-child').each(
function()
{
var child = $(this);
alert('xx');
});
Upvotes: 2
Views: 6769
Reputation: 166001
Assuming I've understood your question correctly, you are trying to get all of the input
elements that are children of a div
:
mainDiv.find("div > input");
If you want all descendant input
elements, not only direct children:
mainDiv.find("div input");
Note that you need to use find
, not children
. The children
method only looks at direct children, and returns them if they match the selector. The selector div input
will not match any of the direct children (the only direct child is a div
) so no elements are returned.
Upvotes: 10
Reputation: 76880
Well, you are actually creating a div with
var mainDiv = $('<div>');
then you append a <div>
to it
var div = $('<div>').appendTo(mainDiv);
Then you append a <input>
to the <div>
$('<input type="checkbox">').appendTo(div);
So the input are not direct children of mainDiv , they are descendant so you have to do
mainDiv.find('input').each
Upvotes: 0