I would like to make all the children of the parent div focusable but not the grandchildren.
Like this:
<div class="parent" >
<div class="child1" > <!-- should be focused-->
<div class="grandchild" ></div> <!-- shouldn't be focused-->
</div>
<div class="child2" > <!-- should be focused-->
<div class="grandchild" ></div> <!-- shouldn't be focused-->
</div>
<div class="child3" > <!-- should be focused-->
<div class="grandchild" ></div> <!-- shouldn't be focused-->
</div>
<div class="child4" > <!-- should be focused-->
<div class="grandchild" ></div> <!-- shouldn't be focused-->
</div>
<div class="child5" > <!-- should be focused-->
<div class="grandchild" ></div> <!-- shouldn't be focused-->
<!-- more divs-->
</div>
</div>
Is it possible to do it with pure HTML, CSS?
Does using tabindex=0on the parent div make all the children focusable? Or do I need to individually add a tabindex to each of the children?
Using the tab button on keyboard
Setting tab-index to -1 prevents the element from being focused by pressing Tab. This can be automated with JS:
document.querySelectorAll('.parent > * > *').forEach((e)=>{
e.setAttribute("tabindex", -1);
})
<div class="parent">
<div class="child1">
<!-- should be focused-->
<div class="grandchild"></div>
<!-- shouldn't be focused-->
</div>
<div class="child2">
<!-- should be focused-->
<div class="grandchild"></div>
<!-- shouldn't be focused-->
</div>
<div class="child3">
<!-- should be focused-->
<div class="grandchild"></div>
<!-- shouldn't be focused-->
</div>
<div class="child4">
<!-- should be focused-->
<div class="grandchild"></div>
<!-- shouldn't be focused-->
</div>
<div class="child5">
<!-- should be focused-->
<div class="grandchild"></div>
<!-- shouldn't be focused-->
<!-- more divs-->
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With