Skip to content

Commit

Permalink
Throw more useful errors
Browse files Browse the repository at this point in the history
  • Loading branch information
domoscargin committed Sep 7, 2023
1 parent b56cebf commit 0fc25bc
Showing 1 changed file with 25 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -32,28 +32,46 @@ 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) {
throw new MissingElementError(
'Skip link: the linked HTML element does not exist',
{
cause: cause instanceof Error ? cause : undefined
}
)
}

this.$linkedElement = $linkedElement
this.$module.addEventListener('click', () => this.focusLinkedElement())
}

/**
* 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(
`Skip link: $module "href" attribute does not contain a hash`
)
}

return document.getElementById(linkedElementId)
const linkedElement = document.getElementById(linkedElementId)

if (!linkedElement) {
throw new Error(
`Skip link: Target selector "#${linkedElementId}" not found`
)
}

return linkedElement
}

/**
Expand Down

0 comments on commit 0fc25bc

Please sign in to comment.