Home > Mobile >  JQuery select all where arbitrary parent has class X
JQuery select all where arbitrary parent has class X

Time:01-12

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 >
    <div >
        <input name="layout[]" type="checkbox" >
    </div>
</div>
<!-- note some inputs will have "d-none" on the grandparent -->
<div >
    <div >
        <input name="layout[]" type="checkbox" >
    </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

CodePudding user response:

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');
  • Related