What is the best way to make the children of a parent div focusable without including the grandchildren divs in the focus?

I want to ensure that only the children of the main div are able to receive focus, not the grandchildren.

Here is an example:

<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>

Can this be achieved using only HTML and CSS?

If I use tabindex=0 on the parent div, will it make all the children focusable? Or do I have to individually assign a tabindex to each child?

Navigating with the tab key on a keyboard

Answer №1

By setting the tab-index to -1, you can prevent an element from being focused when the Tab key is pressed. This functionality can be easily achieved using JavaScript:

document.querySelectorAll('.parent > * > *').forEach((element) => {
  element.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>

Answer №2

According to the information provided in the MDN documentation,

  • It is recommended that only interactive elements have a tabindex attribute.
  • Avoid assigning tabindex values higher than 0 whenever possible.

Setting a positive value for the tabindex attribute on an element allows it to be focused, but this focusability does not automatically extend to its children.

In standard HTML, achieving focusability for every child of an element without individually assigning tabindex="0" to them seems impractical. One convenient approach would be to utilize JavaScript as shown below:

/// enable focus for specific elements
Array.from(
  document.querySelectorAll(".focusable")
).forEach(item => item.tabIndex = 0);

/// disable focus for certain elements
Array.from(
  document.querySelectorAll(".grandchild")
).forEach(item => item.tabIndex = -1);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exploring the concept of JavaScript closures and the pitfalls of name clobber

Is it possible for variables defined inside an inner function with the same name as a variable in an outer function to be isolated from the outer variable? function() { var myTest = "hi there"; ( function( myLocalTest ) { myLocalTest = "go ...

Experiencing difficulties posting on route due to receiving an undefined object instead of the expected callback in Node Js

I am working on implementing a feature in my application where users can create a favorite route. When a user adds a campground to their favorites, the ID of the campground is saved in an array within the schema. The process involves checking if the campgr ...

Error Message: Undefined Constructor for Firebase Google Authentication

Hey there! I've been working on integrating Firebase google authentication into my project. Unfortunately, I encountered an error while testing it out. Here's the error message that appeared in the console: Uncaught (in promise) TypeError: Cannot ...

Is all of the app fetched by Next.js when the initial request is sent?

After doing some research online, I learned that Next.js utilizes client-side routing. This means that when you make the first request, all pages are fetched from the server. Subsequent requests will render those pages in the browser without needing to com ...

Is it possible to scroll the grid horizontally?

I have a grid that scrolls vertically, with columns adjusting their width automatically. .grid { display: grid; overflow-y: auto; grid-template-columns: repeat(auto-fit, minmax($min-column-width, 1fr)); } Now, I'm attempting to create a horizon ...

Transitioning from Event-driven Object Oriented design to Redux structure

I currently have a structure that is mostly object-oriented and I am considering migrating to React/Redux due to handling issues with events. I have various modules with objects structured like this: User { getName() getSurname() etc... } These obj ...

Quickly redesigning the appearance of file input using javascript and jquery. Seeking assistance to correct css issues on jsfiddle

Hey there, I've been working on styling the input[type="file"] element and could use some assistance. Like the saying goes, "One JSfiddle is worth 1000 words," so here's the link to my example: --- For more details, click here: http://jsfiddle.n ...

What is the goal of JSON.parse(JSON.stringify(x))?

During my recent project work, I stumbled upon the following code snippet: let newParams = JSON.parse(JSON.stringify(initialParams)); I'm curious - what exactly does this code achieve? ...

Can someone provide guidance on how to send serialized data using a jQuery.getScript() request?

Is it feasible to make a request for an external JS file while simultaneously sending serialized data in that same request? I want to provide some values to validate the request, but without including those values in the request URL. Upon receiving the po ...

div added on the fly not showing up

I'm attempting to dynamically add a div to a webpage using Chrome. Despite following several instructional guides, the code does not seem to be working as expected. I have added style attributes to make it more visible, but the element is not showing ...

What is the best way to display an HTML page in the bottom right corner instead of within a div?

I am trying to display the content of an HTML page in the bottom right corner of another page using my JavaScript script. However, I do not want to insert a div into the page and then load the content inside it. Instead, I am looking for an alternative way ...

Using Tween animations with Three.js

I have some queries regarding tween js within three.js. Below is the code snippet where the particles are generated as shown in the image: Image 1 // Code snippet for initializing var scene; var renderer; var container; var stats; var sphere; // Omitted ...

Flex columns with flex items of equal height

I am attempting to create a layout where list items within a column have equal heights. Below is my current code: <ol> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ol> ol { ...

Storing JSON data as a string within JSON format with the help of PHP

When conducting testing, I am looking to utilize Ajax for requesting JSON data from the server. The JSON format that Ajax should receive appears as follows: json=[ {"source":"pa","jsonstring": '{"a":1,"b":2,"c":3}'}, {"source":"pa","json ...

Internet Explorer experiencing off-screen menu loading issue

Currently, I am in the process of developing a website for my sister but facing challenges with cross-browser compatibility. The menu appears off-screen when using Internet Explorer, while it looks fine on Chrome. Despite various attempts to adjust alignme ...

Delicate seams break up the different sections of the webpage

I'm facing an issue with my website where thin lines are appearing between each section when previewed in Safari and Chrome, but not in Firefox (as shown in the images). I've checked the CSS code for each section in Dreamweaver, where the lines d ...

Enhance your website with the powerful combination of jQuery Cycle and

My issue lies with the jQuery cycle plugin and its timeout feature. I am utilizing the scrollLeft effect and aiming to have it continuously scrolling, resembling a news ticker. Setting timeout: 0 does not achieve this as it completely disables auto-scroll ...

What is the best way to simultaneously create a customer and add a card with Stripe?

When attempting to initialize a customer for the first time, I encounter an issue where using a Stripe token more than once raises an error. The process involves a form submission on the client side and handling the token creation on the server side: var ...

When the drawer is opened, there is a strange phenomenon of all buttons being mysteriously clicked

Currently, I am working on a single-page web application utilizing React and Material UI, along with React-Mini-Router for routing. The app features a side drawer that is activated by clicking a hamburger icon located in the top app bar. Each item in the d ...

Set iframe scroll to match the height of the user's screen resolution

Can the height of an iframe scroll be adjusted to match the size of the screen (browser)? Essentially replacing the default browser scroll with the iframe scroll. Here's what I'm looking to achieve: Currently, my browser scroll is disabled: < ...