0

How can you determine if an html element has a "value" property/attribute?

Textarea example:

let textarea = document.createElement("textarea");
textarea.innerHTML = "Sike!"; 
console.log(textarea.hasAttribute("value")); // returns false (expected true)
console.log(textarea.hasOwnProperty("value")); // returns false (expected true)
console.log(textarea.value); // returns "Sike!";

Div Example:

let div = document.createElement("div");
div.innerHTML = "Sike!"; 
console.log(div.hasAttribute("value")); // returns false (expected false)
console.log(div.hasOwnProperty("value")); // returns false (expected false)
console.log(div.value); // returns undefined; (expected thrown error)
Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • @bsplosion I don't think that question has anything to really do with this one. – VLAZ Sep 18 '18 at 19:10
  • Is it an input, select, button, or textarea? it has a value! the possible tag names are small enough that being able to determine in other ways is simply not necessary. – Kevin B Sep 18 '18 at 19:11
  • 1
    @LonnieBest i mean, not necessarily. Several of those answers have things that work in your case. – Kevin B Sep 18 '18 at 19:17
  • 1
    But `in` works with the prototype chain. Try it `let a = {val: 42}; let b = Object.create(a); console.log('val' in b);` – VLAZ Sep 18 '18 at 19:23
  • 1
    Looks like `.value` is a getter property that is inherited from the prototype of the textarea element object. But really this should not matter anywhere. What is your [actual problem](https://meta.stackexchange.com/q/66377)? – Bergi Sep 18 '18 at 19:23
  • console.log(("value" in elementVariableName)); works. Thanks all. – Lonnie Best Sep 18 '18 at 19:35

1 Answers1

0

You could test if a property named 'value' exists in the (non-standard) __proto__ property of your element:

let textarea = document.createElement("textarea");
console.log('value' in textarea.__proto__);
console.log('foo' in textarea.__proto__);
connexo
  • 53,704
  • 14
  • 91
  • 128
  • 2
    You shouldn't need to test `__proto__` - doing `value in textarea` should work fine and check the prototype chain already. If it didn't work, then `__proto__` wouldn't work either, because the property could be coming from the prototype's prototype, which would require a recursive check of all prototypes. – VLAZ Sep 18 '18 at 19:32
  • 1
    Don't use `__proto__` any more, not in code, explanations, or SO answers! It's deprecated by `Object.getPrototypeOf`. – Bergi Sep 18 '18 at 20:21