Course contentsShow
← Web Development
Lesson 1088 of 2,98219. Keyboard Navigation and FocusFree lesson

Moving Focus After Element Removal

Techniques for moving focus to appropriate elements when the currently focused element is removed from the DOM.

Moving Focus After Element Removal

What you'll learn: How to prevent keyboard users from losing their place when the currently focused element disappears from the page.

When you delete or hide a DOM element that currently has keyboard focus, the browser typically moves focus back to the <body> element. For keyboard users, this is jarring—it's like reading a book and suddenly being thrown back to the table of contents. They lose their place and must navigate all over again from the top.

Why This Matters

Imagine a user navigates through a list of items, presses a "Delete" button, and the item disappears. If focus isn't managed, they're suddenly back at the beginning of the page. They have to tab through everything again to reach the next item—frustrating and inefficient.

The Solution: Explicit Focus Transfer

Before removing an element that has focus, explicitly move focus to a logical nearby element. Think of it as handing off the baton in a relay race—you pass control smoothly rather than dropping it.

Common strategies:

  • Next sibling: Move focus to the next item in a list
  • Previous sibling: If it was the last item, focus the previous one
  • Parent container: If no siblings exist, focus the parent section
  • Related action: Focus an "Add New" button or return to a main control

Example Pattern (Conceptual)

When the user activates a delete button:

  1. Check if the target element has focus
  2. Identify where focus should move (next item, previous item, parent)
  3. Call the focus() method on that destination element
  4. Then remove the original element

Without this intentional handoff, keyboard navigation breaks and accessibility suffers significantly.

Key Takeaway: Always move focus to a logical nearby element before removing the currently focused element, preventing keyboard users from losing their navigation context.