Search code examples
javascripthtmlelements

Best ways to check if an HTMLElement contains the value property


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)

Solution

  • To test if an object has a property, simply use 'prop' in obj:

    [...document.body.querySelectorAll('*')].forEach((el)=> {
      console.log(el.tagName + ' contains: ' + readEl(el));
    })
    
    function readEl(el) {
      return 'value' in el ? el.value : el.textContent || false;
    }
    <p>para</p>
    <input value="input" />
    <textarea>textarea</textarea>
    <div>div</div>