下面的例子参考了下面的 HTML sn-p:
<div id="test">
Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>
节点将被以下 JavaScript 引用:
var x = document.getElementById('test');
element.innerHTML
Sets or gets the HTML syntax describing the element's descendants
x.innerHTML
// => "
// => Warning: This element contains <code>code</code> and <strong>strong language</strong>.
// => "
这是 W3C 的DOM Parsing and Serialization Specification 的一部分。请注意,它是 Element 对象的属性。
node.innerText
Sets or gets the text between the start and end tags of the object
x.innerText
// => "Warning: This element contains code and strong language."
-
innerText 是由 Microsoft 引入的,并且有一段时间不受 Firefox 的支持。 2016 年 8 月,innerText 更名为 adopted by the WHATWG,并在 v45 中添加到 Firefox。
-
innerText 为您提供了一种风格感知的文本表示,它试图与浏览器呈现的内容相匹配,这意味着:
-
innerText 应用 text-transform 和 white-space 规则
-
innerText 修剪行之间的空白并在项目之间添加换行符
-
innerText 不会返回不可见项目的文本
-
innerText 将返回 textContent 用于从未渲染过的元素,例如 <style /> 和 `
-
Node 元素的属性
node.textContent
Gets or sets the text content of a node and its descendants.
x.textContent
// => "
// => Warning: This element contains code and strong language.
// => "
虽然这是 W3C standard,但 IE
- 不知道样式,因此会返回被 CSS 隐藏的内容
- 不触发回流(因此性能更高)
-
Node 元素的属性
node.value
这取决于您定位的元素。对于上面的示例,x 返回一个 HTMLDivElement 对象,该对象没有定义 value 属性。
x.value // => null
输入标签(<input />),比如define a value property,指的是“控件中的当前值”。
<input id="example-input" type="text" value="default" />
<script>
document.getElementById('example-input').value //=> "default"
// User changes input to "something"
document.getElementById('example-input').value //=> "something"
</script>
来自docs:
注意:对于某些输入类型,返回值可能与
用户输入的值。例如,如果用户输入一个
将非数字值转换为<input type="number">,返回值
可能是一个空字符串。
示例脚本
这是一个示例,它显示了上述 HTML 的输出:
var properties = ['innerHTML', 'innerText', 'textContent', 'value'];
// Writes to textarea#output and console
function log(obj) {
console.log(obj);
var currValue = document.getElementById('output').value;
document.getElementById('output').value = (currValue ? currValue + '\n' : '') + obj;
}
// Logs property as [propName]value[/propertyName]
function logProperty(obj, property) {
var value = obj[property];
log('[' + property + ']' + value + '[/' + property + ']');
}
// Main
log('=============== ' + properties.join(' ') + ' ===============');
for (var i = 0; i < properties.length; i++) {
logProperty(document.getElementById('test'), properties[i]);
}
<div id="test">
Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>
<textarea id="output" rows="12" cols="80" style="font-family: monospace;"></textarea>