jquery select first child with class of a parent with class

108,203

Solution 1

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:

Solution 2

You're passing an invalid selector to children(). Instead of

.children('.line_item_wrapper :first')

try

.children('.line_item_wrapper').first()

Solution 3

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();

Solution 4

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

Share:
108,203
1252748
Author by

1252748

Updated on November 16, 2020

Comments

  • 1252748
    1252748 over 2 years

    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!