innerText, innerHTML和值之间的区别?

在JavaScript中,innerHTMLinnerTextvalue有什么区别?

366578 次浏览

InnerText属性对内容进行html编码,将<p>转换为&lt;p&gt;,等等。如果你想插入HTML标签,你需要使用InnerHTML

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

InnerText将仅以纯文本形式返回页面的文本值,其中每个元素在换行符上,而innerHTML将返回body标记内所有内容的HTML内容,而childNodes将返回一个节点列表,顾名思义。

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

下面的例子引用了下面的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由微软引入,Firefox一度不支持。2016年8月,innerText由WHATWG采纳,并在v45中添加到Firefox。
  • innerText为你提供了一个样式感知的文本表示,它试图匹配浏览器呈现的内容,这意味着:
    • innerText应用text-transformwhite-space规则
    • innerText修饰行与行之间的空白,并在项之间添加换行符
    • innerText将不会返回不可见项的文本
    • 李< / ul > < / >
    • 对于从未像<style />和'那样呈现的元素,innerText将返回textContent
    • 属性


    node.textContent

    虽然这是一个W3C标准,它不被IE <支持;9.

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


    node.value

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

    x.value // => null
    

    例如,输入标记(<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>
    

    文档:

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

MutationObservers而言,设置innerHTML会产生一个childList突变,因为浏览器会删除该节点,然后添加一个值为innerHTML的新节点。

如果你设置了innerText,会生成一个characterData突变。

简单地说:

  1. innerText将按原样显示值,并忽略可能存在的任何HTML格式 李。< / >
  2. innerHTML将显示值并应用任何HTML格式。

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>

HTML元素的__ABC0和innerHTML 都返回内部部分

只有__ABC0和innerHTML的区别是:innerText返回HTML元素(整个代码)作为字符串并在屏幕上显示HTML元素(作为HTML代码),而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;
}
<p><b>Inner text below. It inject string as it is into the element.</b></p>
<p id="innertext"></p>
<br>
<p><b>Inner html below. It renders the string into the element and treat as part of html document.</b></p>
<p id="innerhtml"></p>

要添加到列表中,innerText将保留你的text-transforminnerHTML习惯。

innerText属性设置或返回指定节点及其所有后代的纯文本文本内容,而innerHTML属性获取和设置元素中的纯文本或HTML内容。与innerText不同,innerHTML让你处理HTML富文本,不会自动对文本进行编码和解码。

Innerhtml将应用HTML代码

内文将把内容作为文本,所以如果你有HTML标签,它将显示为文本

@rule:

innerHTML

  • write:无论你写入ele.innerHTML的字符串是什么,ele (html文件中元素的代码)将与它写入String中完全相同。

  • read:无论你从ele.innerHTML读取到一个字符串,字符串将完全相同,它是在ele (html文件)。

  • =比;.innerHTML不做任何修改用于您的读/写

innerText

  • write:当你将一个String对象写入ele.innerText时,String对象中的任何html reserved special character都将首先被编码转换成html格式,然后存储到ele中。

    • 你的String中的<p>将变成ele中的&lt;p&gt;
  • read:当你从ele.innerText读取到一个字符串,

    1. ele中的任何html reserved special character解码还原为可读的文本格式,

      • ele中的&lt;p&gt;将会变成你的String中的<p>
    2. ele中的任何(有效)html tag将是删除——因此它将变成“纯文本”;

      • ele中的if <em>you</em> can将变成你的String中的if you can
      • 关于无效html tag

        • 如果在ele (html代码)中有一个无效的html tag,并且你从__abc2读取,该标签如何被删除?

          ——这("如果有一个无效的html tag原始")不应该(不可能)发生

        • ,但是有可能你通过.innerHTML (raw)在ele中写了一个无效的html tag——然后,这可能由浏览器自动修复。

      • don take (-interpret) this is step [1.]][2。带着命令 ——不,把它当作步骤[1.]][2。[/p> .]同时执行

        我的意思是,如果[1.]]会在转换后形成一个新的标签,[2.])并不能移除它

        (——cuz [2.]]考虑在转换过程中ele中有哪些字符,而不是转换后它们变成的字符)

    3. 然后存储到字符串中。


jsfiddle: with explanation .

  • (^在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>
*/