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

Why does the innerText property of the html element only show the innerText of the body element?

console.log(document.getElementsByTagName('html')['0'].textContent);
console.log(document.getElementsByTagName('html')['0'].innerText);
<!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>

textContent 属性 正在打印 html 元素内的所有文本内容,不包括标签。它还打印所有的空白和新行。因此,为了获得没有空格和新行的文本,我使用了 innerText 属性 但它没有在 title 元素内打印文本,只是在 p 元素内打印文本。为什么 innerText 属性 没有像我预期的那样工作?

您的以下代码按预期行为工作。我想你对他们感到困惑。看看这里 MDN

一对:

  1. textContent获取所有元素的内容,包括<script><style>元素,而innerText没有,只显示人类可读个元素。

  2. innerText 知道样式并且不会 return 隐藏 元素的文本,而 textContent确实。

要删除白色-space 和新行,您可以使用正则表达式替换。

// remove new-line and white space with replace
console.log(document.getElementsByTagName('html')['0'].textContent.replace(/[\n\r]+|[\s]{2,}/g, ' '));
<!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>

根据MDN

Node.innerText is a property that represents the "rendered" text content of a node and its descendants. As a getter, it approximates the text the user would get if they highlighted the contents of the element with the cursor and then copied to the clipboard.

<title> 元素的内容不会呈现为文本内容,当然也无法突出显示或复制到剪贴板。因此,它不会被Node.innerText编辑return。

有趣的是,document.getElementsByTagName('title')['0'].innerText return <title> 元素的内容。对此做了一些阅读,它是 explained in the spec:

If this element is not being rendered, or if the user agent is a non-CSS user agent, then return the same value as the textContent IDL attribute on this element.

This step can produce surprising results, as when the innerText attribute is accessed on an element not being rendered, its text contents are returned, but when accessed on an element that is being rendered, all of its children that are not being rendered have their text contents ignored.

@user9218974,body 下的每一个东西,假设被呈现为网页,无论 HEAD 包含什么,它都只是用于呈现的信息和资源。

所以在这里,在您的代码中,HEAD 包含 metatitle,它们只是页面的 info/meta。所以或多或少你可以说你的工作区是body.

内的内容

现在,如果您想要 title 的文本,您需要使用 'document.title'