javascript innerText 和innerHTML 的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19030742/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:07:16  来源:igfitidea点击:

Difference between innerText and innerHTML

javascriptdom

提问by user2819851

What is the difference between innerHTML, innerTextand childNodes[].valuein JavaScript?

JavaScript 中的innerHTML,innerText和 有什么区别childNodes[].value

采纳答案by alejo802

Unlike innerText, though, innerHTMLlets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerTextretrieves and sets the content of the tag as plain text, whereas innerHTMLretrieves and sets the content in HTML format.

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

回答by fny

The examples below refer to the following HTML snippet:

以下示例引用了以下 HTML 代码段:

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

The node will be referenced by the following JavaScript:

该节点将由以下 JavaScript 引用:

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



element.innerHTML

element.innerHTML

Sets or gets the HTML syntax describing the element's descendants

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

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

This is part of the W3C's DOM Parsing and Serialization Specification. Note it's a property of Elementobjects.

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



node.innerText

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."
  • innerTextwas introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016, innerTextwas adopted by the WHATWGand was added to Firefox in v45.
  • innerTextgives you a style-aware, representation of the text that tries to match what's rendered in by the browser this means:
    • innerTextapplies text-transformand white-spacerules
    • innerTexttrims white space between lines and adds line breaks between items
    • innerTextwill not return text for invisible items
  • innerTextwill return textContentfor elements that are never rendered like <style />and `
  • Property of Nodeelements
  • innerText由 Microsoft 推出,有一段时间不受 Firefox 支持。2016 年 8 月,innerTextWHATWG 采用,并在 v45 中添加到 Firefox。
  • innerText为您提供风格感知的文本表示,尝试匹配浏览器呈现的内容,这意味着:
    • innerText适用text-transformwhite-space规则
    • innerText修剪行之间的空白并在项目之间添加换行符
    • innerText不会返回不可见项目的文本
  • innerText将返回textContent从未渲染过的元素<style />和 `
  • Node元素属性



node.textContent

node.textContent

Gets or sets the text content of a node and its descendants.

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

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

While this is a W3C standard, it is not supported by IE < 9.

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

  • Is not aware of styling and will therefore return content hidden by CSS
  • Does not trigger a reflow (therefore more performant)
  • Property of Nodeelements
  • 不知道样式,因此将返回由 CSS 隐藏的内容
  • 不触发回流(因此性能更高)
  • Node元素属性



node.value

node.value

This one depends on the element that you've targeted. For the above example, xreturns an HTMLDivElementobject, which does not have a valueproperty defined.

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

x.value // => null

Input tags (<input />), for example, do define a valueproperty, which refers to the "current value in the control".

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

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

From the docs:

文档

Note: for certain input types the returned value might not match the value the user has entered. For example, if the user enters a non-numeric value into an <input type="number">, the returned value might be an empty string instead.

注意:对于某些输入类型,返回值可能与用户输入的值不匹配。例如,如果用户在 中输入非数字值<input type="number">,则返回值可能是空字符串。



Sample Script

示例脚本

Here's an example which shows the output for the HTML presented above:

下面是一个示例,它显示了上述 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>

回答by guymid

InnerTextproperty html-encodes the content, turning <p>to &lt;p&gt;, etc. If you want to insert HTML tags you need to use InnerHTML.

InnerText物业HTML编码的内容,转向<p>&lt;p&gt;等,如果你想插入你需要使用HTML标签InnerHTML

回答by Balkishan

In simple words:

简单来说:

  1. innerTextwill show the value as is and ignores any HTMLformatting which may be included.
  2. innerHTMLwill show the value and apply any HTMLformatting.
  1. innerText将按原样显示值并忽略HTML可能包含的任何格式。
  2. innerHTML将显示值并应用任何HTML格式。

回答by kaushik0033

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

To further refine it and retrieve the value Alec for example, use another .childNodes[1]

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

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

回答by Nikos

In terms of MutationObservers, setting innerHTMLgenerates a childListmutation due to the browsers removing the node and then adding a new node with the value of innerHTML.

就 而言MutationObservers,由于浏览器删除节点,然后添加值为 的新节点,因此设置会innerHTML产生childList突变innerHTML

If you set innerText, a characterDatamutation is generated.

如果您设置innerTextcharacterData则会生成一个突变。

回答by NickAth

The innerTextproperty returns the actual textvalue of an html element while the innerHTMLreturns the HTML content. Example below:

innerText属性返回html 元素的实际文本值,而innerHTML返回HTML content. 下面的例子:

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>

回答by Satish Chandra Gupta

The only difference between innerTextand innerHTMLis that innerTextinsert string as it is into the element, while innerHTMLrun it as html content.

innerText和之间的唯一区别innerHTMLinnerText将字符串按原样插入元素,而innerHTML将其作为 html 内容运行。

const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';
document.getElementById('innertext').innerText = ourstring;
document.getElementById('innerhtml').innerHTML = ourstring;
.name{
color:red;
}
<h3>Inner text below. It inject string as it is into the element.</h3>
<div id="innertext"></div>
<br />
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>
<div id="innerhtml"></div>

回答by scrblnrd3

InnerTextwill only return the text value of the page with each element on a newline in plain text, while innerHTMLwill return the HTML content of everything inside the bodytag, and childNodeswill return a list of nodes, as the name suggests.

InnerText只会以纯文本形式innerHTML返回带有换行符的每个元素的页面的文本值,而将返回body标签内所有内容的 HTML 内容,childNodes并将返回节点列表,顾名思义。

回答by Teiem

to add to the list, innerText will keep your text-transform, innerHTML wont

要添加到列表中,innerText 将保留您的文本转换,而innerHTML 不会