Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the child's of a parent div focusable but not the grandchild divs?

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

like image 864
User not found Avatar asked Nov 23 '25 11:11

User not found


1 Answers

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>
like image 101
Spectric Avatar answered Nov 26 '25 05:11

Spectric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!