user1392897
user1392897

Reputation: 851

jQuery: Find all DIVs containing specific elements

I want to adjust the height of a div if certain conditions are true. Specifically, I want to find any .element divs that contain a textarea and in which the error message div exists.

$('.element').each(function() {
    if ( $(this).find('textarea') && $(this).find('.error-message') ) {
        $(this).css('min-height', '80px');
    }   
}); 

Given this structure, only the middle div should get the extra height:

<div class="element">
  <input type="text" />
</div>
<div class="element">
  <div class="error-message"></div>
  <textarea></textarea>
</div>
<div class="element">
  <input type="text" />
</div>

Upvotes: 1

Views: 1144

Answers (3)

Milind Anantwar
Milind Anantwar

Reputation: 82251

You can use chaining of :has selector here:

 $('.element:has(.error-message):has(textarea)').css('min-height', '80px');

$('.element:has(.error-message):has(textarea)').css('min-height', '80px');
div {
  border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
  <input type="text" />
</div>
<div class="element">
  <div class="error-message"></div>
  <textarea></textarea>
</div>
<div class="element">
  <input type="text" />
</div>

Upvotes: 3

j08691
j08691

Reputation: 208030

.length will be your friend here:

$('.element').each(function() {
  if ($(this).find('textarea').length && $(this).find('.error-message').length) {
    $(this).css('min-height', '80px');
  }
});
div {
  border: 1px solid #999;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="element">
  <input type="text" />
</div>
<div class="element">
  <div class="error-message"></div>
  <textarea></textarea>
</div>
<div class="element">
  <input type="text" />
</div>

While you're finding the proper elements with your selectors, in order to test them in an if condition you'll want to use .length which returns the number of elements in the jQuery object.

Upvotes: 3

You can verify the length of the error-message class like this:

var elem = $('.element');
if(elem.find('.error-message').length > 0) {
  // Code here
}

Upvotes: 0

Related Questions