我有一个 HTML 页面,我只需要文本(所有文本节点)。
示例 HTML
<span>hello <strong>sir</strong></span>
期望的输出
hello sir
最佳答案
假设您只想要 body
元素的子元素...
示例 HTML
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title> Example</title>
</head>
<body>
a <div>b<span>c</span></div>
</body></html>
JavaScript
var body = document.body;
var textContent = body.textContent || body.innerText;
console.log(textContent); // a bc
您需要检查 textContent
,因为我们的好 friend IE 使用 innerText
。
如果你有一个像jQuery 这样的图书馆,事情就会容易得多。 ,即 $('body').text()
。
也可以在服务器端实现,如strip_tags()
在 PHP 中。但是,如果您只想要 body
元素,则需要使用 DOM 解析器(例如 DOMDocument)向下钻取它。 .
关于javascript - 如何从 HTML 文档中获取仅文本(无标签)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5321739/