Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

JQuery select all where arbitrary parent has class X

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Using JQuery 3.6 and Bootstrap 5

>Solution :

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');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading