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
一对:
同时
textContent
获取所有元素的内容,包括<script>
和<style>
元素,innerText
不会,只显示人类可读元素。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/