• Returns an element of tag name TN 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

    • TN extends TagName = "*"

      Tag name of the Element representation of target.

    Parameters

    • target: undefined | null | Target

      Element, EventTarget, or CSS selector.

    • Optionalparent: null | Target

      Optional Element, EventTarget, or CSS selector for parent.

    Returns ElementOf<TN> | null

    Element of tag name TN 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<"input">("#test");
    // Returns the element and asserts as an `<input>`

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

    Usage with Element

    function handleButtonClick(event: MouseEvent): void {
    const buttonElement = toElement<"button">(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?.();
    }