首页 > 解决方案 > 从 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>.

标签: javascriptvariablesextractinnerhtml

解决方案


使用DOMParser.

var parser = new DOMParser();
var doc = parser.parseFromString(aVariable, "text/html");
var elm = doc.querySelector(".content");

推荐阅读