Reputation: 2395
I want to use jQuery to hide one of the divs below, not its content. What is the jQuery selector I can use to target the div that has the input with the name address1
?
What I'm trying to do is hide div with class .snipcart-input
where it has an input with the id address1
<div class="snipcart-input">
<input id="address1" type="text" name="address1" class="snipcart-input__input snipcart__font--secondary snipcart__font--bold">
</div>
<div class="snipcart-input">
<input id="address2" type="text" name="address2" class="snipcart-input__input snipcart__font--secondary snipcart__font--bold">
</div>
Upvotes: 1
Views: 40
Reputation: 50291
You can use each, find & addClass. each
will iterate all the div with this class and will find
input this id
. This will give an object which have length
property. So if that object have child with specified requirement then length will be more than 1. You can use hide
or addClass
to hide element
$('.snipcart-input').each(function(i, v) {
let hasChildrenWithId = $(v).find('input#address1');
if (hasChildrenWithId.length > 0) {
$(v).addClass('hide')
}
})
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="snipcart-input">
<input id="address1" type="text" name="address1" class="snipcart-input__input snipcart__font--secondary snipcart__font--bold">
</div>
<div class="snipcart-input">
<input id="address2" type="text" name="address2" class="snipcart-input__input snipcart__font--secondary snipcart__font--bold">
</div>
Upvotes: 0
Reputation: 337560
You can use the :has()
selector to achieve what you need:
$('.snipcart-input:has(#address1)').hide();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="snipcart-input">
Address1:
<input id="address1" type="text" name="address1" class="snipcart-input__input snipcart__font--secondary snipcart__font--bold">
</div>
<div class="snipcart-input">
Address2:
<input id="address2" type="text" name="address2" class="snipcart-input__input snipcart__font--secondary snipcart__font--bold">
</div>
Upvotes: 3