How can i select only the first child of a particular class of a parent with a particular class for the purposes of clone()
?
You're passing an invalid selector to children()
.
Instead of
.children('.line_item_wrapper :first')
try
.children('.line_item_wrapper').first()
Your problems is that your selector is wrong, in a few ways:
parents()
returns one, two or many elements that match the selector passed to the method; to limit yourself to the first-matched element use closest()
(which returns one, or no, elements that match the passed-in selector).
Your first use of the children()
method returns both elements, since they both match the supplied selector and have the class of line_item_wrapper
; you need to explicitly state which of the two you want, you can either use the :first
selector (or the first()
method), or the :first-child
selector.
The second call to the children()
method finds the children of the first element matched by the selector, which you don't seem to want.
Anyway, if you must use the parent (starting from the same $(this)
element):
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first').clone(true);
Or:
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first().clone(true);
Or:
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper:first-child').clone(true);
Or, frankly, a simpler approach (but this does dispense with the parent class-name check):
var form1 = $(this).prevAll('.line_item_wrapper:last');
Or:
var form1 = $(this).siblings('.line_item_wrapper').eq(0);
References:
Try this:
var $firstDiv = $(".sector_order > .line_item_wrapper:eq(0)");
This will get you the first direct descendant of sector_order
with the class line_item_wrapper
.
Example fiddle
Use :first-child
var form1 = $(this).closest('.sector_order').find(':first-child');
OR .first()
var form1 = $(this).closest('.sector_order').find('.line_item_wrapper').first();