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

标签 javascript html ecmascript-6 ecmascript-5

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知道样式并且不会返回隐藏元素的文本,而textContent会。

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

// 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>

关于javascript - 为什么html元素的innerText属性只显示body元素的innerText?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52912391/

相关文章:

javascript - jquery 在函数中的 Focusout 上执行双重触发代码

html - 如果我为一个组件设置像素,它在每台显示器上的行为是否相同?

css - 为什么灰色背景颜色仅出现在 Google Chrome 中?

javascript - 获取select的值

javascript - 使用字符串的模板语法不是函数错误

javascript - 通过循环类(原型(prototype))属性使 Mixins 工作

javascript - 从其他组件访问激活的路由数据

javascript - 需要双击输出单选按钮选择

javascript - 创建对象时,如果值未定义,则不包含在新对象中

javascript - 创建将两个文件中的数据与公共(public)列组合在一起的映射 - 但数据不一对一匹配