safe-get-element
TypeScript icon, indicating that this package has built-in type declarations

1.0.3 • Public • Published

safe-get-element

Runtime-based type safety for the commonly used document.getElementById method. This method prevents you from having to manually check if a returned element is not null, and you can optionally provide a tagName that will assert the given element type.

Quick Start

npm i safe-get-element
<!DOCTYPE html>
<html>
  <button id='my-button'></button>
</html>
import { safeGetElement } from 'safe-get-element'

const button = safeGetElement('my-button', 'button') // HTMLButtonElement

// without safe-get-element

const button = document.getElementById('my-button')

if (button === null) {
  throw new Error('Cannot find button!')
}

if (button.tagName !== 'BUTTON') {
  throw new Error('Button is not of type HTMLButtonElement')
}

API

safeGetElement(id: string)

Returns: HTMLElement

When used with just an id, the API will assert the queried element is not null and return it. Otherwise, it throws an error.

safeGetElement(id: string, assertType: TagName)

TagName is a generic that is constrained to keyof HTMLElementTagNameMap from TypeScript's lib.dom.d.ts.

Returns: HTMLElementTagNameMap[TagName]

When passed an assertType, the API asserts the queried element eixsts and its respective tagName matches the associated assertType. If it does, it returns the element as the associated DOM Interface.

What about getElementsByTagName, querySelector, or querySelectorAll?

These methods already support some level of type safety!

// getElementsByTagName
const buttons1 = document.getElementsByTagName('button') // HTMLCollectionOf<HTMLButtonElement>
const myButton1 = buttons.find(button => button.id === 'my-button') // HTMLButtonElement

// querySelector
const myButton2 = document.querySelector('button') // HTMLButtonElement | null

if (myButton2 !== null) {
  // HTMLButtonElement
}

// querySelectorAll
const buttons2 = document.querySelectorAll('button') // NodeListOf<HTMLButtonElement>
const myButton3 = buttons.find(button => button.id === 'my-button') // HTMLButtonElement

Package Sidebar

Install

npm i safe-get-element

Weekly Downloads

5

Version

1.0.3

License

MIT

Unpacked Size

4.66 kB

Total Files

6

Last publish

Collaborators

  • ethan_arrowood