从 Javascript 变量中提取特定的 HTML 容器
Extract specific HTML container from Javascript variable
如何从包含 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");
这应该有效!
var data= $(html);
var content= data.children('#content').html();
这应该有效
var all= new DOMParser().parseFromString(aContent) ;
var contentHtml = all.querySelector('.content').outerHTML
您可以使用DOMParser
界面
The DOMParser
interface provides the ability to parse XML or HTML source code from a string into a DOM Document.
const html = `<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>`
const domparser = new DOMParser()
const doc = domparser.parseFromString(html, 'text/html')
const elem = doc.querySelector('section.content')
console.log(elem.outerHTML)
如何从包含 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");
这应该有效!
var data= $(html);
var content= data.children('#content').html();
这应该有效
var all= new DOMParser().parseFromString(aContent) ;
var contentHtml = all.querySelector('.content').outerHTML
您可以使用DOMParser
界面
The
DOMParser
interface provides the ability to parse XML or HTML source code from a string into a DOM Document.
const html = `<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>`
const domparser = new DOMParser()
const doc = domparser.parseFromString(html, 'text/html')
const elem = doc.querySelector('section.content')
console.log(elem.outerHTML)