First search Element inside another Element if it exists in jQuery

Asked

Viewed 678 times

1

I’m having a problem finding an Element within Another and checking if it is first element, see the structure:

<div class="form-group">
  <input type="text" id="teste1" placeholder="Texto">
  <label for="teste1">Texto</label>
  <p class="help-block">Teste.</p>
</div>
<div class="form-group">
  <label>Texto</label>
  <p>Texto</p>
  <p class="help-block">Teste.</p>
</div>

I’m looking to select the tag label within the form-group but only if he’s the first element, I tried this way on jQuery:

if ( $('.form-group').children().first().is('label') ) {
  $(this).parent().css("padding-top", "0");
}

But the answer is false.

1 answer

2


$('.form-group') returns an array containing all class elements.

$('.form-group').each(function() {
    var primeiro = $(this).children().first();
    if($(primeiro).is('label')) {
    $(primeiro).parent().css('padding-top', '0');
  }
});

example: https://jsfiddle.net/re7ktwaq/

  • I imagined that the jQuery after the $(document).ready read it could fetch the elements, nor believed that needed to pass an array first, thanks to the example.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.