HTML元素-是否存在“值”属性或属性?

时间:2018-09-18 19:06:10

标签: javascript dom

如何确定html元素是否具有“值”属性/属性?

文本区域示例:

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!";

细分示例:

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)

1 个答案:

答案 0 :(得分: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__);