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
Difference between innerText and innerHTML
提问by user2819851
What is the difference between innerHTML
, innerText
and childNodes[].value
in JavaScript?
JavaScript 中的innerHTML
,innerText
和 有什么区别childNodes[].value
?
采纳答案by alejo802
Unlike innerText
, though, innerHTML
lets you work with HTML rich text and doesn't automatically encode and decode text. In other words, innerText
retrieves and sets the content of the tag as plain text, whereas innerHTML
retrieves 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
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 Element
objects.
这是 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."
innerText
was introduced by Microsoft and was for a while unsupported by Firefox. In August of 2016,innerText
was adopted by the WHATWGand 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
appliestext-transform
andwhite-space
rulesinnerText
trims white space between lines and adds line breaks between itemsinnerText
will not return text for invisible items
innerText
will returntextContent
for elements that are never rendered like<style />
and `- Property of
Node
elements
innerText
由 Microsoft 推出,有一段时间不受 Firefox 支持。2016 年 8 月,innerText
被WHATWG 采用,并在 v45 中添加到 Firefox。innerText
为您提供风格感知的文本表示,尝试匹配浏览器呈现的内容,这意味着:innerText
适用text-transform
和white-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
Node
elements
- 不知道样式,因此将返回由 CSS 隐藏的内容
- 不触发回流(因此性能更高)
Node
元素属性
node.value
node.value
This one depends on the element that you've targeted. For the above example, x
returns an HTMLDivElementobject, which does not have a value
property defined.
这取决于您所针对的元素。对于上面的示例,x
返回一个没有定义属性的HTMLDivElement对象value
。
x.value // => null
Input tags (<input />
), for example, do define a value
property, 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
InnerText
property html-encodes the content, turning <p>
to <p>
, etc. If you want to insert HTML tags you need to use InnerHTML
.
InnerText
物业HTML编码的内容,转向<p>
对<p>
等,如果你想插入你需要使用HTML标签InnerHTML
。
回答by Balkishan
In simple words:
简单来说:
innerText
will show the value as is and ignores anyHTML
formatting which may be included.innerHTML
will show the value and apply anyHTML
formatting.
innerText
将按原样显示值并忽略HTML
可能包含的任何格式。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 innerHTML
generates a childList
mutation 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 characterData
mutation is generated.
如果您设置innerText
,characterData
则会生成一个突变。
回答by NickAth
The innerText
property returns the actual textvalue of an html element while the innerHTML
returns 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 innerText
and innerHTML
is that innerText
insert string as it is into the element, while innerHTML
run it as html content.
innerText
和之间的唯一区别innerHTML
是innerText
将字符串按原样插入元素,而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
InnerText
will only return the text value of the page with each element on a newline in plain text, while innerHTML
will return the HTML content of everything inside the body
tag, and childNodes
will 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 不会