diff --git a/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs b/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs index cae167bc0f..9a8f4819cf 100644 --- a/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs +++ b/packages/govuk-frontend/src/govuk/components/skip-link/skip-link.mjs @@ -32,12 +32,16 @@ export class SkipLink extends GOVUKFrontendComponent { this.$module = $module // Check for linked element - const $linkedElement = this.getLinkedElement() - if (!$linkedElement) { - throw new MissingElementError('The linked HTML element does not exist') + try { + const $linkedElement = this.getLinkedElement() + this.$linkedElement = $linkedElement + } catch (cause) { + const message = cause instanceof Error ? cause : new Error(String(cause)) + throw new MissingElementError('The linked HTML element does not exist', { + message + }) } - this.$linkedElement = $linkedElement this.$module.addEventListener('click', () => this.focusLinkedElement()) } @@ -45,15 +49,25 @@ export class SkipLink extends GOVUKFrontendComponent { * Get linked element * * @private - * @returns {HTMLElement | null} $linkedElement - DOM element linked to from the skip link + * @throws {Error} If the "href" attribute does not contain a hash + * @throws {Error} If the element with the specified ID does not exist + * @returns {HTMLElement} $linkedElement - DOM element linked to from the skip link */ getLinkedElement() { const linkedElementId = this.getFragmentFromUrl() if (!linkedElementId) { - return null + throw new Error( + `The Skip Link's "href" attribute does not contain a hash` + ) } - return document.getElementById(linkedElementId) + const linkedElement = document.getElementById(linkedElementId) + + if (!linkedElement) { + throw new Error(`Element with ID "${linkedElementId}" does not exist`) + } + + return linkedElement } /**