Imagine a function whose signature looks like:
function readElement(element: HTMLElement): string;
To implement the function you will have to check if the element is using the value
property (i.e. HTMLInputElement
) or the textContent
property (i.e. SpanElement
) and get the respective property. What I am asking is a couple of ways that can implement readElement
, are foolproof and have high browser compatibility.
Here is a list of ways I've used to tackle the problem in the past:
element.value !== undefined
element.constructor.hasOwnProperty("value")
typeof element.value === "string"
[HTMLInputElement, HTMLTextAreaElement,...].some(proto => element instanceof proto)