【问题标题】:Difference between innerText, innerHTML and value?innerText、innerHTML 和 value 之间的区别?
【发布时间】:2013-10-02 13:39:52
【问题描述】:

JavaScript 中的innerHTMLinnerTextvalue 有什么区别?

【问题讨论】:

  • @tymeJV 老实说,与innerText(MSIE 对 textContext 的非标准实现)的区别并不重要。
  • 除了innerText在Firefox中不起作用:textContent似乎在所有主流浏览器中都可以使用,所以只需使用textContent而不是innerText。
  • 重要提示:以上 3 cmets 不再有效。 innerText 已添加到标准中,并受到所有主要浏览器的支持。 textContent 现在被 IE>=9 支持,并且可以在大多数情况下代替 innerText 使用(奖励,它更快),但是两者之间存在差异,所以在某些情况下你不能交换它们。
  • 2019 年更新:innerText 在所有浏览器中都得到了很好的支持。 Firefox 从版本 45 开始支持它。caniuse.com/#search=innertext
  • 我很惊讶这里没有解决安全问题。 innerHTML 是 XSS 攻击的已知漏洞。也就是说,innerText 也不是 100% 安全的。 stackoverflow.com/questions/52707031/does-innertext-prevent-xssblog.cloudboost.io/…

标签: javascript dom innerhtml innertext


【解决方案1】:

下面的例子参考了下面的 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-transformwhite-space 规则
    • innerText 修剪行之间的空白并在项目之间添加换行符
    • innerText 不会返回不可见项目的文本
  • innerText 将返回 textContent 用于从未渲染过的元素,例如 &lt;style /&gt; 和 `
  • 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

输入标签(&lt;input /&gt;),比如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

注意:对于某些输入类型,返回值可能与 用户输入的值。例如,如果用户输入一个 将非数字值转换为&lt;input type="number"&gt;,返回值 可能是一个空字符串。


示例脚本

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

【讨论】:

【解决方案2】:

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

【讨论】:

  • 在接受的答案@jor 在另一个答案下面的评论中粘贴此处非常重要:“只是为了清楚起见:这仅适用于设置值时。当您获取值时,HTML 标记被简单地剥离你得到纯文本。”
【解决方案3】:

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

【讨论】:

  • 只是为了清楚起见:这只适用于设置值时。当你 GETTING 值时,HTML 标记被简单地剥离,你得到纯文本。
【解决方案4】:

简单来说:

  1. innerText 将按原样显示值并忽略任何可能的 HTML 格式 包括在内。
  2. innerHTML 将显示该值并应用任何 HTML 格式。

【讨论】:

    【解决方案5】:

    innerTextinnerHTML返回 HTML 元素的内部部分

    innerTextinnerHTML 之间的唯一区别在于: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>

    【讨论】:

      【解决方案6】:
      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);
      

      【讨论】:

        【解决方案7】:

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

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

        【讨论】:

          【解决方案8】:

          innerText 属性将文本内容设置或返回为指定节点及其所有后代的纯文本,而innerHTML 属性获取并设置元素中的纯文本或 HTML 内容。与innerText 不同,innerHTML 允许您使用 HTML 富文本,并且不会自动对文本进行编码和解码。

          【讨论】:

            【解决方案9】:

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

            【讨论】:

              【解决方案10】:

              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>

              【讨论】:

                【解决方案11】:

                要添加到列表中,innerText 将保留您的 text-transforminnerHTML 不会。

                【讨论】:

                  【解决方案12】:

                  innerhtml 将应用 html 代码

                  innertext 会将内容作为文本放置,因此如果您有 html 标签,它将仅显示为文本

                  【讨论】:

                    猜你喜欢
                    • 2013-10-25
                    • 1970-01-01
                    • 2016-05-14
                    • 2020-07-12
                    • 1970-01-01
                    • 2018-04-22
                    相关资源
                    最近更新 更多