@laserware/dominator
    Preparing search index...

    Function toElement

    • Returns an element of type E for the specified Element or EventTarget. You can also pass in a CSS selector string, which will attempt to find the element in the DOM.

      Note

      This differs from asElement in that it will never throw if you pass in an invalid, null, or undefined target, rather it will return null. The asElement function only accepts an Element or EventTarget whereas this function also accepts a CSS selector.

      Type Parameters

      Parameters

      • target: undefined | null | Target

        Element, EventTarget, or CSS selector.

      • Optionalparent: null | Target

        Optional Element, EventTarget, or CSS selector for parent.

      Returns null | E

      Element of type E if it exists, otherwise returns null.

      This function accepts a parent element to accommodate for cases where the target is a CSS selector and we want to limit the search to the specified parent.

      Usage with CSS Selector

      const elementThatExists = toElement<HTMLInputElement>("#test");
      // Returns the element and asserts as an `<input>`

      const elementNoExists = toElement<HTMLButtonElement>("#missing");
      // Returns null

      Usage with Element

      function handleButtonClick(event: MouseEvent): void {
      const buttonElement = toElement<HTMLButtonElement>(event.currentTarget);

      // Note that need to use optional chaining because the return value of
      // toElement be `null` (even though we *know* that `currentTarget` is defined):
      buttonElem?.focus?.();
      }