JavaScript中innerHTML, innerText和value的区别是什么?


当前回答

下面的例子引用了下面的HTML片段:

<div id="test">
   Warning: This element contains <code>code</code> and <strong>strong language</strong>.
</div>

该节点将被下面的JavaScript引用:

var x = document.getElementById('test');


element.innerHTML

设置或获取描述元素后代的HTML语法

x.innerHTML
// => "
// =>   Warning: This element contains <code>code</code> and <strong>strong language</strong>.
// => "

这是W3C DOM解析和序列化规范的一部分。注意,这是Element对象的属性。


node.innerText

设置或获取对象的开始标记和结束标记之间的文本

x.innerText
// => "Warning: This element contains code and strong language."

innerText was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016, innerText was adopted by the WHATWG and was added to Firefox in v45. innerText gives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means: innerText applies text-transform and white-space rules innerText trims white space between lines and adds line breaks between items innerText will not return text for invisible items innerText will return textContent for elements that are never rendered like <style /> and ` Property of Node elements


node.textContent

获取或设置节点及其子节点的文本内容。

x.textContent
// => "
// =>   Warning: This element contains code and strong language.
// => "

虽然这是W3C标准,但IE < 9不支持它。

不知道样式,因此将返回由CSS隐藏的内容 不会触发回流流(因此性能更好) 节点元素属性


node.value

这取决于您所针对的元素。对于上面的例子,x返回一个HTMLDivElement对象,该对象没有定义value属性。

x.value // => null

例如,输入标记(< Input />)确实定义了一个值属性,它指的是“控件中的当前值”。

<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>

从文档中可以看出:

注意:对于某些输入类型,返回值可能不匹配 用户输入的值。例如,如果用户输入 非数值转换为<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>

其他回答

innerText属性返回html元素的实际文本值,而innerHTML返回html内容。在下面的例子:

var element = document.getElementById('hello'); element.innerText = '<strong> hello world </strong>'; console.log('The innerText property will not parse the html tags as html tags but as normal text:\n' + element.innerText); console.log('The innerHTML element property will encode the html tags found inside the text of the element:\n' + element.innerHTML); element.innerHTML = '<strong> hello world </strong>'; console.log('The <strong> tag we put above has been parsed using the innerHTML property so the .innerText will not show them \n ' + element.innerText); console.log(element.innerHTML); <p id="hello"> Hello world </p>

就mutation观察者而言,设置innerHTML会生成一个childList突变,因为浏览器会删除节点,然后添加一个带有innerHTML值的新节点。

如果设置innerText,则会生成characterData突变。

@rule:

innerHTML

write:写入ele的任何字符串。innerHTML, ele (html文件中元素的代码)将与它在String中所写的完全相同。 阅读:你从ele中读到的任何东西。innerHTML到一个字符串,字符串将完全相同,它是在ele (html文件)。

=> .innerHTML将不会为您的读/写做任何修改

innerText

write: when you write a String to the ele.innerText, any html reserved special character in the String will be encoded into html format first, then stored into the ele. eg: <p> in your String will become &lt;p&gt; in the ele read : when you read from the ele.innerText to a String, any html reserved special character in the ele will be decoded back into a readable text format, eg: &lt;p&gt; in the ele will become back into <p> in your String any (valid) html tag in the ele will be removed -- so it becomes "plain text" eg: if <em>you</em> can in the ele will become if you can in your String about invalid html tag if there is an invalid html tag originally in the ele (the html code), and you read from.innerText, how does the tag gets removed? -- this ("if there is an invalid html tag originally") should not (is not possible to) happen but its possible that you write an invalid html tag by .innerHTML (in raw) into ele -- then, this may be auto fixed by the browser. dont take (-interpret) this as step [1.] [2.] with an order -- no, take it as step [1.] [2.] are executed at the same time -- I mean, if the decoded characters in [1.] will form a new tag after the conversion, [2.] does not remove it (-- cuz [2.] considers what characters are in the ele during the conversion, not the characters they become into after the conversion) then stored into the String.


有解释

(^在js文件的注释中包含了更多的解释,+在console.log中输出 下面是一个简化的视图,带有一些输出。 (自己尝试代码,也不能保证我的解释是100%正确的。))

<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite"></p>
<p id="textWrite"></p>
// > @basic (simple)
// read
var ele_mainContent = document.getElementById('mainContent');
alert(ele_mainContent.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.        // >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_mainContent.innerText); // This is a sample sentennce for Reading.                         // >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"

// write
var str_WriteOutput = "Write <strong>this</strong> sentence to the output.";
var ele_htmlWrite = document.getElementById('htmlWrite');
var ele_textWrite = document.getElementById('textWrite');
ele_htmlWrite.innerHTML = str_WriteOutput;
ele_textWrite.innerText = str_WriteOutput;

alert(ele_htmlWrite.innerHTML); // Write <strong>this</strong> sentence to the output.               // >" + => `.innerHTML` will **not make any modification** for your read/write
alert(ele_htmlWrite.innerText); // Write this sentence to the output.                                // >" 2. any (valid) `html tag` in the `ele` will be **removed** -- so it becomes "plain text"                     
alert(ele_textWrite.innerHTML); // Write &lt;strong&gt;this&lt;/strong&gt; sentence to the output.   // >" any `html reserved special character` in the String will be **encoded** into html format first               
alert(ele_textWrite.innerText); // Write <strong>this</strong> sentence to the output.               // >" 1. any `html reserved special character` in the `ele` will be **decoded** back into a readable text format,  

// > @basic (more)
// write - with html encoded char
var str_WriteOutput_encodedChar = "What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?";
var ele_htmlWrite_encodedChar = document.getElementById('htmlWrite_encodedChar');
var ele_textWrite_encodedChar = document.getElementById('textWrite_encodedChar');
ele_htmlWrite_encodedChar.innerHTML = str_WriteOutput_encodedChar;
ele_textWrite_encodedChar.innerText = str_WriteOutput_encodedChar;

alert(ele_htmlWrite_encodedChar.innerHTML); // What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?
alert(ele_htmlWrite_encodedChar.innerText); // What if you have <strong>encoded</strong> char in the sentence?
alert(ele_textWrite_encodedChar.innerHTML); // What if you have &amp;lt;strong&amp;gt;encoded&amp;lt;/strong&amp;gt; char in &lt;strong&gt;the&lt;/strong&gt; sentence?
alert(ele_textWrite_encodedChar.innerText); // What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?


// > @note-advance: read then write 
var ele__htmlRead_Then_htmlWrite = document.getElementById('htmlRead_Then_htmlWrite');
var ele__htmlRead_Then_textWrite = document.getElementById('htmlRead_Then_textWrite');
var ele__textRead_Then_htmlWrite = document.getElementById('textRead_Then_htmlWrite');
var ele__textRead_Then_textWrite = document.getElementById('textRead_Then_textWrite');

ele__htmlRead_Then_htmlWrite.innerHTML = ele_mainContent.innerHTML;
ele__htmlRead_Then_textWrite.innerText = ele_mainContent.innerHTML;
ele__textRead_Then_htmlWrite.innerHTML = ele_mainContent.innerText;
ele__textRead_Then_textWrite.innerText = ele_mainContent.innerText;

alert(ele__htmlRead_Then_htmlWrite.innerHTML); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__htmlRead_Then_htmlWrite.innerText); // This is a sample sentennce for Reading.
alert(ele__htmlRead_Then_textWrite.innerHTML); // This is a &lt;strong&gt;sample&lt;/strong&gt; sentennce for Reading.
alert(ele__htmlRead_Then_textWrite.innerText); // This is a <strong>sample</strong> sentennce for Reading.
alert(ele__textRead_Then_htmlWrite.innerHTML); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_htmlWrite.innerText); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_textWrite.innerHTML); // This is a sample sentennce for Reading.
alert(ele__textRead_Then_textWrite.innerText); // This is a sample sentennce for Reading.


// the parsed html after js is executed
/*
<html><head>
<meta charset="utf-8">
<title>Test</title>
</head>
<body>
<p id="mainContent">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlWrite">Write <strong>this</strong> sentence to the output.</p>
<p id="textWrite">Write &lt;strong&gt;this&lt;/strong&gt; sentence to the output.</p>
<!-- P2 -->
<p id="htmlWrite_encodedChar">What if you have &lt;strong&gt;encoded&lt;/strong&gt; char in <strong>the</strong> sentence?</p>
<p id="textWrite_encodedChar">What if you have &amp;lt;strong&amp;gt;encoded&amp;lt;/strong&amp;gt; char in &lt;strong&gt;the&lt;/strong&gt; sentence?</p>
<!-- P3 @note: -->
<p id="htmlRead_Then_htmlWrite">This is a <strong>sample</strong> sentennce for Reading.</p>
<p id="htmlRead_Then_textWrite">This is a &lt;strong&gt;sample&lt;/strong&gt; sentennce for Reading.</p>
<p id="textRead_Then_htmlWrite">This is a sample sentennce for Reading.</p>
<p id="textRead_Then_textWrite">This is a sample sentennce for Reading.</p>

</body></html>
*/

var element = document.getElementById("main");
var values = element.childNodes[1].innerText;
alert('the value is:' + values);

要进一步细化它并检索值Alec(例如,使用另一个.childNodes[1])

var element = document.getElementById("main");
var values = element.childNodes[1].childNodes[1].innerText;
alert('the value is:' + values);

不过,与innerText不同的是,innerHTML允许您使用HTML富文本,并且不会自动对文本进行编码和解码。换句话说,innerText检索并将标记的内容设置为纯文本,而innerHTML检索并设置为HTML格式的内容。