javascript - 删除 body 标签之外的所有内容

标签 javascript html

我有一个包含来自外部 HTML 页面的 responseText 的变量:

textFromFile = myRequest.responseText;

我怎样才能删除正文标签之外的所有内容? 我可以使用 Regex 删除字符串 (textFromFile) 中的所有 HTML 标记,但在此之前,如果有人可以帮助我删除正文标记之外的所有字符(换句话说,我将不胜感激,只需将字符串/单词保留在 HTML 页面的 body 标签内即可)。

----编辑部分----

我正在阅读的 HTML 文件是:

<html>
<head> title </head>
<body>
<p> Hello World! <br/>
<a href = ”link.html”> Click <b> here </b> </a> <br/>
Goodbye world!
</p>
</body>
</html>

当我申请时:

var doc = new DOMParser().parseFromString(myRequest.responseText, "text/html");
            alert(doc.body.innerHTML);

响应是:

title 

<p> Hello World! <br>
<a href="”link.html”"> Click <b> here </b> </a> <br>
Goodbye world!
</p>

这不应该是这种情况,因为“标题”在正文标签之外。

最佳答案

使用 DOM 解析器解析 HTML:

var doc = new DOMParser().parseFromString(myRequest.responseText, "text/html");

然后简单地使用innerHTML(或outerHTML):

doc.body.innerHTML;

var string = "<!DOCTYPE html><title>Title</title><p>Hello</p>",
    doc = new DOMParser().parseFromString(string, "text/html");
document.getElementById('inner').textContent = doc.body.innerHTML;
document.getElementById('outer').textContent = doc.body.outerHTML;
pre {
  background: #ddd;
  font-family: monospace;
  padding: .5em;
}
The inner HTML of &lt;body&gt; is:
<pre id="inner"></pre>
The outer HTML of &lt;body&gt; is:
<pre id="outer"></pre>

关于javascript - 删除 body 标签之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35262172/

相关文章:

javascript - 如何动态地将一个数组中的数据移动到另一个单独的数组

javascript - 将 AJAX 内容放入 DOM 中或通过 onClick 事件向 jQuery 注册对象?

javascript - 当部分宽度设置为 0 时隐藏文本

html - 在柱形图中绘制两条线谷歌图表

javascript - 是否可以在 React 之外获取 React 属性?

javascript - 使用javascript读取谷歌搜索历史记录

javascript - 在javascript中重新加载后保存变量值

javascript - 延迟后显示 cookie 警报

javascript - DOM 操作问题

javascript - 删除iframe的主体背景颜色