From cf4d53cb89764af07044630b3068e53a9bb116da Mon Sep 17 00:00:00 2001 From: Simon <154227189+simonhype@users.noreply.github.com> Date: Mon, 21 Oct 2024 13:36:05 +0200 Subject: [PATCH] Deal with element parents not being present When fetching the siblings of an element, the parent node might not be present yet. This can happen when the v-roving-tabindex-container directive and the v-roving-tabindex directive are used in separate components and the siblings of the v-roving-tabindex elements are fetched during mounting. It leads to an error when then trying to get the children of that non-existing parent. This case is handled in this commit by just not returning any siblings. As a result, the tabindex is not set correctly on the elements at first. But this seems to fix itself later on when attempting to set the tabindex again in the update lifecycle method. --- src/RovingTabindex.js | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/src/RovingTabindex.js b/src/RovingTabindex.js index e1c8e51..d5b7a16 100644 --- a/src/RovingTabindex.js +++ b/src/RovingTabindex.js @@ -8,13 +8,16 @@ import { getContainerConfig } from "./RovingTabindexContainer"; * @param {HTMLElement} el - Current [data-roving-tabindex] element * @returns {HTMLElement[]} Sibling tabindex elements */ -const getSiblings = el => - Array.from( - el.closest(`[${ATTR_CONTAINER}]`).querySelectorAll(`[${ATTR_ITEM}]`) - ).filter( +const getSiblings = el => { + const elements = el.closest(`[${ATTR_CONTAINER}]`)?.querySelectorAll(`[${ATTR_ITEM}]`); + if (!elements) { + return []; + } + return Array.from(elements).filter( $el => $el.closest(`[${ATTR_CONTAINER}]`) === el.closest(`[${ATTR_CONTAINER}]`) ); +} /** * Enable an an element's tabindex by it's index