Element representation of target.
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 you need to use optional chaining because the return value of
// toElement may be `null` (even though we *know* that `currentTarget` is defined):
buttonElement?.focus?.();
}
Returns an element of type
Efor the specified Element or EventTarget. You can also pass in a CSS selector string, which will attempt to find the element in the DOM.This differs from
asElementin that it will never throw if you pass in an invalid,null, orundefinedtarget, rather it will returnnull. TheasElementfunction only accepts an Element or EventTarget whereas this function also accepts a CSS selector.