Reputation: 161
I'm trying to figure out a jquery selector where I can grab all DOM elements with name A, that ALSO have a grandparent with class X. Here's an example HTML, I will have many of these
<div class="interface_controlgroup">
<div class="form-switch me-3">
<input name="layout[]" type="checkbox" class="form-check-input">
</div>
</div>
<!-- note some inputs will have "d-none" on the grandparent -->
<div class="interface_controlgroup d-none">
<div class="form-switch me-3">
<input name="layout[]" type="checkbox" class="form-check-input">
</div>
</div>
...
<!-- repeated -->
Now I would like to select all inputs, as well as all inputs where the grandparent has d-none
let all_inputs = $('input[name=layout\\[\\]]');
//cannot use this because the entire section may be hidden when this is run
let hidden_inputs = $('input[name=layout\\[\\]]:hidden');
//I need something more like
let hidden_inputs = $('input[name=ide_layout_std\\[\\]]'.parent().parent()".d-none");
I am looking for a solution that allows me to only select when the parent's parent has a certain class, but I don't know how to create this match. I also can't rely on ":hidden"
in the jquery selector because the entire section/page may be hidden when this javascript is running.
Using JQuery 3.6 and Bootstrap 5
Upvotes: 0
Views: 26
Reputation: 781013
You can use the x > y
child selector to solve this. x > * > z
matches z
with a grandparent x
(the parent in the middle can be anything).
let hidden_inputs = $('.d-none > * > input[name=ide_layout_std\\[\\]]:hidden');
Upvotes: 1