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>
.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.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments