Reputation: 7504
I have a hierarchy of divs and there is a input box which has unique name attribute.
$(document).ready(function(){
$(".first > input[name='inp']").hide();
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="first">
First
<div class="second">
Second
<label for="inp">Label Input</label>
<input type="text" name="inp" />
</div>
</div>
I need to hide the div first if it has any input child with that specific unique name.
I used this selector input[name='inp']
for input, How do I remove the whole first div now, parent().hide()
removes only the first parent.
Note: There are multiple divs with the same class name, so I cannot use class selector.
Upvotes: 1
Views: 301
Reputation: 4368
Use :has()
selector, selects all elements that have one or more elements inside of them, that matches the specified selector.:
$(document).ready(function(){
$(".first:has(input[name='inp'])").hide()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="first">
First
<div class="second">
Second
<label for="inp">Label Input</label>
<input type="text" name="inp" />
</div>
</div>
Upvotes: 3
Reputation: 43441
First select all inputs, then hide it's parents.
$(document).ready(function() {
$("input[name='inp']").closest('.first').hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first">
First 1
<div class="second">
Second
<label for="inp">Label Input</label>
<input type="text" name="inp" />
</div>
</div>
<div class="first">
First 2
<div class="second">
Second
<label for="inp">Label Input</label>
<input type="text" name="inp" />
</div>
</div>
<div class="first">
First 3
<div class="second">
Second
<label for="inp">Label Input</label>
<input type="text" name="inp3" />
</div>
</div>
Your parent().hide()
does not work, because it selects .second
, not .first
. There is also .parents()
to select all parents, so it would be .parents().eq(1).hide()
Upvotes: 3