为什么`HTMLelement.innerText`添加换行符(\ n)?

时间:2018-12-08 22:04:14

标签: javascript jquery angularjs element getelementbyid

我发现HTMLelement.innerText的这种奇怪行为我无法理解。 这是一个问题的示例:

// HTML
<div>
    <article id="editor"></article>
</div>

// JavaScript
var editor = document.getElementById('editor');
console.log(editor.innerHTML); // prints "\n"

// From 3rd party libraries
var jqueryExample = jquery.parseHTML('<div><article></article></div>')[0];
console.log(jqueryExample.innerHTML); // prints ""

var angularjsExample = angular.element('<div><article></article></div>')[0];
console.log(angularjsExample.innerHTML); // prints ""

如您所见,当我使用document.getElementById时,出于某种原因,元素的innerHTML具有\n。但是,如果我使用jquery.parseHTMLangular.element,则不会添加\n,它会按原样返回。

如果HTML包含更多内容,则会更有趣:

// HTML
<div>
    <article id="editor">
        <h1>Test</h1>
        <p>Foo</p>
    </article>
</div>

// JavaScript
var editor = document.getElementById('editor');
console.log(editor.innerText); // prints "Test\nFoo"

但是jquery.parseHTMLangular.element的{​​{1}}打印innerText。为什么会这样?

Newlines

4 个答案:

答案 0 :(得分:1)

它不添加任何新行。它仅按“原样”输出内容。在第一种情况下,它输出一个空字符,因此您看不到它。在第二种情况下,有四个新行(请在editor-2示例的下面检查有关如何将相同内容输出为单行)。

var editor1 = document.getElementById('editor-1');
console.log('editor-1: [' + editor1.innerHTML + ']'); //-> "[]"

var editor2 = document.getElementById('editor-2');
console.log('editor-2: [' + editor2.innerHTML + ']'); //-> "[<h1>Test</h1><p>Foo</p>]"
<div>
  <article id="editor-1"></article>
  <article id="editor-2"><h1>Test</h1><p>Foo</p></article>
</div>

答案 1 :(得分:1)

INTO没问题(这只是获取元素的一种方法)。您正在做不同的事情。 getElementById找到浏览器呈现的元素,jQuery代码正在创建一个新元素,因此它可能与第一个元素不同。

答案 2 :(得分:1)

从文档中: 1

  

HTMLElement接口的innerText属性表示节点及其后代的“已渲染”文本内容。作为一种吸气剂,它近似于用户使用光标突出显示元素的内容然后将其复制到剪贴板时将获得的文本。

在我的浏览器(Chrome 61)上,我看到它在字符串中插入了两个换行符:

var editor = document.getElementById('editor');
console.log(editor.innerText); // prints "Test\nFoo"
console.log(editor.innerText.length);
console.log(Array.from(editor.innerText))
<script src="//unpkg.com/angular/angular.js"></script>
<div>
    <article id="editor">
        <h1>Test</h1>
        <p>Foo</p>
    </article>
</div>

答案 3 :(得分:0)

即使您向此元素添加了li,该元素您要尝试console.log的内容仍然为空。因为您正在尝试从此元素进行console.log innerHTML。如果您尝试使用console.log(element.value),它将显示为undefined,因为没有值。