Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  37] [ 6]  / answers: 1 / hits: 120009  / 12 Years ago, thu, november 15, 2012, 12:00:00

How can i select only the first child of a particular class of a parent with a particular class for the purposes of clone()?



<div class=sector_order>

<div class=line_item_wrapper>
SELECT THIS DIV
</div>

<div class=line_item_wrapper>
NOT THIS DIV
</div>

</div>


I am trying like this:



var form1 = $(this)
.parents('.sector_order')
.children('.line_item_wrapper')
.children().clone(true)


and get both inner divs with the class line_item_wrapper, but I get an empty object when I try with this addition:



children('.line_item_wrapper :first')


Thanks!


More From » jquery

 Answers
52

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:




[#81969] Wednesday, November 14, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gerardob

Total Points: 571
Total Questions: 115
Total Answers: 96

Location: Cyprus
Member since Mon, Oct 24, 2022
2 Years ago
;