首页 文章

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

提问于
浏览
0

我发现 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.elementinnerText 打印 TestFoo . 这是为什么???

4 回答

  • 0

    这对 getElementById 来说不是问题(这只是获取元素的一种方法) . 你正在做不同的事情 . getElementById 找到一个由浏览器呈现的元素,一个jquery代码创建一个新元素,因此它可能与第一个元素不同 .

  • 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

    即使你向这个元素添加了一些li,你尝试console.log的那个元素仍然是空的 . 因为你正试图从这个元素中调用console.log innerHTML . 如果您将尝试console.log(element.value),它将显示未定义的,因为没有值 .

  • 1

    来自Docs:1

    HTMLElement接口的innerText属性表示节点及其后代的“呈现”文本内容 . 作为一个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))
    
    <script src="//unpkg.com/angular/angular.js"></script>
    <div>
        <article id="editor">
            <h1>Test</h1>
            <p>Foo</p>
        </article>
    </div>
    

相关问题