nick zoum
nick zoum

Reputation: 7315

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:

Upvotes: 1

Views: 1898

Answers (1)

connexo
connexo

Reputation: 56783

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>

Upvotes: 3

Related Questions