jquery select first child with class of a parent w

2019-02-07 21:46发布

问题:

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!

回答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:

  • closest().
  • eq().
  • find().
  • :first.
  • :first-child.
  • first().
  • :last.
  • parents().
  • prevAll().
  • siblings().


回答2:

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

.children('.line_item_wrapper :first')

try

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


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


回答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