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

Guidance on using an array to filter an object in Javascript

Looking at the object structure in Chrome Dev Tools, it appears like this: obj: { 1: {...}, 2: {...}, 3: {...}, 4: {...}, 5: {...}, } On the other hand, there is a simple array as well: arr: [1,3,5,7] The goal here is to filter the object bas ...

Gliding over the problem with the Azure line

Is there a way to hide the opacity and font on hover? I have tried using outline: 0; in my CSS but there is still a blue line lingering. Any ideas on how to remove it? If you need to see the code and the issue I'm describing, here it is: p { font ...

Auto-fill Textbox from a different Textbox in MVC 4

I am attempting to automatically fill in a textbox based on the value of another textbox, but I am struggling with getting the other textbox to populate. Below is my code - any advice on the best solution would be greatly appreciated. Action Method: [Htt ...

Is it possible to merge two HTML selectors using jQuery?

In my HTML, I have two button elements defined as follows: <input type="button" class="button-a" value="Button a"/> <input type="button" class="button-b" value="Button b"/> When either of these buttons is clicked, I want to trigger the same ...

Tips for identifying the most effective element locator in the DOM with Playwright

Currently, I am in the process of incorporating Playwright tests for a website that supports multiple locales. The majority of the page content is dynamically generated from CMS content (Contentful). I am hesitant about using hardcoded text locators like ...

What is the best way to customize a MaterialUI outlined input using a global theme overrides file?

I've been working on customizing my theme file with overrides, and I've encountered a strange bug while trying to style the outlined input. It seems like there are two borders appearing when these styles are implemented. https://i.stack.imgur.co ...

Switch to a different element by rolling over one

I need assistance with a menu setup where the submenus are located in separate divs on the page. Both the parent elements and submenus have numerical identifying IDs, and I am struggling to create a rollover effect that would automatically open the corresp ...

Is there an issue with JQM plugin due to jQuery's append() function?

I am just starting to learn about jQuery mobile as I develop an app using it. Whenever I click on the Add_details button, I want to add dynamic input fields only once. After saving, if I click on the Add_details button again, I need to append more dynamic ...

Vue and Summernote issue: Model content doesn't display in form when loaded from database

I am having an issue with my form that uses the Summernote wysiwyg editor multiple times. When I fill out the form, everything works correctly - the model is updated, content is displayed, and the data is saved to the database. However, when I try to edit ...

utilizing the JavaScript SDK to send alerts to a user's friends on Facebook

I am attempting to send a notification to a user's friend using the JS SDK on a Facebook canvas app, but I'm encountering this error in the console: POST https://graph.facebook.com/16542203957691/notifications? 400 (OK) jquery.min.js:140 c.exten ...

Should I serialize a 2D array in JSON format and send it as two separate arrays, or is

When it comes to sending a 2-dimensional array (along with several other variables) to PHP using jQuery.ajax(), I have a couple of options in mind: One option is to serialize to json using JSON-js Another option would be to send both arrays as csv string ...

Incorporate a CSS style element to a hyperlink button in JQuery Mobile

I am trying to apply a style to a link button element using JQuery. The code I have written is not working. Can anyone provide suggestions on how to achieve this? Below is the snippet of the HTML <div data-role="content"> <a href="#" class= ...

Inserting a variable into a JSON string

Within my code, I have a basic variable containing strings that are converted into a JSON object. My goal is to create an input field where a person's name can be entered and added to the text. The current setup looks like this var text = '{"st ...

The height of adjacent divs should be uniform, resize seamlessly, and contain an absolutely positioned element within

Is there a way to make these neighboring divs the same height, responsive to browser window resizing, and with icons positioned on the corners? This method using display:table-cell works in most browsers but fails in Firefox due to a bug that causes the ic ...

Consolidate your jQuery functions to avoid repetition

In my form, I have multiple select inputs organized by theme. Each group has a master select option that allows users to set all selects within the group to the same value (gradescales is a method that provides grades 1-8). How can I streamline this proce ...

I'm encountering an issue trying to launch bigbluebutton HTML5. I attempted to initiate it using "npm start" after installing it with "meteor npm install," but unfortunately, it failed to

I've been attempting to launch the Development environment for bigblubutton-html5, but unfortunately, I encountered an error message after executing this command: npm start Please refer to the tutorial I used: Here's the error message that was ...

Book of Tales displaying Emotion Styling upon initial load only

I'm currently working with the styled api provided by emotion in order to create a custom styled button. const StyledButton = styled(Button)` background-color: ${theme.palette.grey['800']}; width: 50; height: 50; &:hover { ba ...

Having trouble retrieving the necessary data to generate a menu, the getStaticProps function is coming back as undefined

I'm currently working with Next.js 13 & Strapi, and my goal is to create a Menu component utilizing the getStaticProps function. To achieve this, I've implemented a Layout component within the _app.js file, and nested a Menu component inside the ...

What is the best way to position an image alongside text using Vue and Buefy?

I'm looking to add an image next to my text in Vue using Buefy. Take a look at the code I have so far, can someone offer some guidance? <template> <section class="hero is-link is-fullheight-with-navbar"> <div cla ...

What is the best way to arrange elements above and below each other in a single flexbox container?

Currently, I am facing a challenge aligning the number 238,741 and the letter N in Number. There is a padding between the Prize Pool div and the Number Active div. All of these elements are enclosed within a parent container with display set to flex and fl ...