park896
park896

Reputation: 465

jQuery find child based on class selector matching parents

I am trying to find the descendants of a particular node using the jquery .find() method. I have noticed that .find() doesnt match elements based on properties of parents above the current node in the tree. The first find returns 0 elements, but the second find returns the element I was searching for. My question is, is this a limitation of the selector pattern allowed for the find method and is find the only jquery function that has this limitation? I would have expected both of these to return the same element. Also, is there another jquery method that would more succinctly accomplish the same thing as second one. This is a simplified example of what I'm trying to do and I cannot remove the .find('.input-group') as this is an input into my function.

$(document).find('.input-group').find('.form-group .form-control')
$(document).find('.input-group').find('.form-control').filter('.form-group .form-control')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">

<body>
  <div class="form-group">
    <div class="input-group">
      <span class="input-group-addon">
       <input type="checkbox" aria-label="CVV Disabled" value="">
    </span>
      <input id="vtCvv" name="vtCvv" type="password" class="form-control" required="true" data-bv-field="vtCvv">
    </div>
  </div>
</body>

</html>

Upvotes: 2

Views: 14490

Answers (2)

Gega Gagua
Gega Gagua

Reputation: 92

$('.form-group .input-group').find('.form-control');

Upvotes: 0

jmore009
jmore009

Reputation: 12923

.find() looks for a descendant of an element. You're trying to find a parent and then a descendant.

You could find .input-group, then traverse backwards through the DOM to the "closest" .form-group using .closest() and then you could navigate down to .form-control like so:

$(document).find('.input-group').closest('.form-group').find(".form-control")

or you could use .parent() to backtrack to .form-group like so:

$(document).find('.input-group').parent().find(".form-control")

I prefer .closest() because if another element were to be added between .input-group and form-group the parent would be different, but .closest would still work.

Upvotes: 4

Related Questions