Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript: check if element can accept a value

Tags:

javascript

dom

I am trying to do something like this (pseudo-code):

if ( element can accept a value )
    element.value = "my new value";
else
    element.innerHTML = "my new value";

So for input, textarea, etc it will set the value, but for div or span it will set the innerHTML.

Or should I simply set both value and innerHTML, since innerHTML is harmless to set for input elements?

like image 246
C C Avatar asked Aug 08 '26 03:08

C C


1 Answers

Basic in operator should do the trick

function hasValue(elem) {
  return 'value' in elem
}

console.log('input', hasValue(document.querySelector('#t1')))
console.log('div', hasValue( document.querySelector('#t2')))
console.log('select', hasValue(document.createElement('select')))
console.log('textarea', hasValue(document.createElement('textarea')))
console.log('h1', hasValue(document.createElement('h1')))
console.log('span', hasValue(document.createElement('span')))
<input type="text" id="t1" />
<div id="t2"></div>
like image 142
epascarello Avatar answered Aug 09 '26 17:08

epascarello