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 need to use optional chaining because the return value of
// toElement be `null` (even though we *know* that `currentTarget` is defined):
buttonElem?.focus?.();
}
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.This differs from
asElement
in that it will never throw if you pass in an invalid,null
, orundefined
target, rather it will returnnull
. TheasElement
function only accepts an Element or EventTarget whereas this function also accepts a CSS selector.