User not found
User not found

Reputation: 519

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

Upvotes: 3

Views: 2146

Answers (2)

Spectric
Spectric

Reputation: 31997

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>

Upvotes: 2

Taur
Taur

Reputation: 564

Referring to the MDN doc,

  • Only interactive components must have a tab index.
  • Avoid using tabindex values greater than 0.

A positive tabindex on an element makes it focusable, but this focusability is not inherited by each of its children.

In pure html, I think there is no way to make each child of an element focusable unless you add a tabindex="0" on them. The easiest way is to use javascript by doing something like

/// make elements focusable
Array.from(
  document.querySelectorAll(".focusable")
).forEach(item => item.tabIndex = 0);

/// make elements not focusable
Array.from(
  document.querySelectorAll(".grandchild")
).forEach(item => item.tabIndex = -1);

Upvotes: 0

Related Questions