为什么html元素的innerText属性只显示body元素的innerText?

Has*_*ash 4 html javascript ecmascript-5 ecmascript-6

console.log(document.getElementsByTagName('html')['0'].textContent);
console.log(document.getElementsByTagName('html')['0'].innerText);
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <p>innnerHtml of paragraph</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

textContent属性打印html元素中除标签之外的所有文本内容.它还可以打印所有空白区域和新线条.因此,为了获得没有空格和新行的文本,我使用了innerText属性,但它没有在title元素中打印文本,只是在p元素中打印了文本.为什么innerText属性不像我预期的那样工作?

Alw*_*nny 5

您的下面的代码按照预期的行为工作.我觉得你对它们感到困惑.看看MDN吧

他们几个:

  1. 虽然textContent获取所有元素(包括元素<script><style>元素)的内容,innerText但只显示人类可读的元素.

  2. innerText知道样式并且不会返回隐藏元素的文本,而是textContent.

要删除空格和换行符,可以使用正则表达式替换.

// remove new-line and white space with replace
console.log(document.getElementsByTagName('html')['0'].textContent.replace(/[\n\r]+|[\s]{2,}/g, ' '));
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>

    <p>innnerHtml of paragraph</p>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)