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

Kim*_*Man 5 javascript jquery element getelementbyid angularjs

我发现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 ""
Run Code Online (Sandbox Code Playgroud)

正如你看到的,当我使用document.getElementById,元素的innerHTML具有\n某种原因。但是,如果我使用jquery.parseHTMLor angular.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"
Run Code Online (Sandbox Code Playgroud)

但是jquery.parseHTMLangular.elementinnerText打印TestFoo。这是为什么???

换行

geo*_*awg 4

来自文档:1

HTMLElementinnerText接口的属性表示节点及其后代的“呈现”文本内容。作为 getter,它近似于用户使用光标突出显示元素内容然后将其复制到剪贴板时将获得的文本。

在我的浏览器(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))
Run Code Online (Sandbox Code Playgroud)
<script src="//unpkg.com/angular/angular.js"></script>
<div>
    <article id="editor">
        <h1>Test</h1>
        <p>Foo</p>
    </article>
</div>
Run Code Online (Sandbox Code Playgroud)