javascript - 从 Javascript 变量中提取特定的 HTML 容器
问题描述
您将如何从包含 html 内容的 JS 变量中提取特定的 html。
在下面的示例中,JS 变量包含从 Fetch API 请求返回的整个 html 内容。我只想从带有 class 的部分中提取内容content
。
变量
const aVariable = fetch(...etc.. etc.. // the returned value)
返回值包含:
<section class="wrapper">
blah blah blah
<div>
blah blah
</div>
<section class="content">
It's the one that I want
<div>
Whoa whoa whoa yeah!
</div>
</section>
blah blah
</section>
我只想要content
但包含它的<section>
.
解决方案
使用DOMParser
.
var parser = new DOMParser();
var doc = parser.parseFromString(aVariable, "text/html");
var elm = doc.querySelector(".content");
推荐阅读
- api - 使用 API 跟踪 edX 或 Udemy 课程进度
- svg - 与 Blink 和 Gecko 相比,为什么 Webkit/Safari(iOS、macOS)以不同的顺序呈现我的 SVG 转换?
- sql - SQL:根据多列中的值选择全部并删除重复的行
- flutter - 无法从 onchange 更新字符串变量
- python-3.x - dot graph graphviz - 为选定节点最近的 x 分支生成图形
- android - 如何避免功能重复
- html - 元素后面的矩形框,同时保留背景图像
- spring-boot - Web.servlet.PageNotFound - 没有 GET 映射
- c# - 在上一个操作完成将 EF Core 2 升级到 EF Core 3.1.3 之前,在此上下文中启动了第二个操作
- python - 如何提取没有索引号的特定列。以及python数据框中的所有行?