【问题标题】:Extract String In-between Div Tag with JavaScript使用 JavaScript 提取字符串中间的 div 标签
【发布时间】:2021-08-17 20:17:29
【问题描述】:

假设我有一个包含 HTML 代码的字符串。此代码的一部分包含电子邮件的预标头。如何提取<div class="preheader" style="font-size: 1px; display: none !important;"> 和关闭</div> 之间的文本?假设打开和关闭 div 将始终保持不变,只有中间的内容发生变化。

some html preceding...
<div class="preheader" style="font-size: 1px; display: none !important;">Email preheader content</div>
some html following...

【问题讨论】:

标签: javascript string


【解决方案1】:

如果你有一个html字符串,你可以把它变成一个DocumentFragment,它就像一个DOM。然后在这个 DOM 中你可以选择你想要获取内容的元素。

这是一个例子:

const html = "your html code here";

const dom = document.createRange().createContextualFragment(html);
// create DocumentFragment

const preheader = dom.querySelector(".preheader"); // Select the element that contains the content

const content = preheader.textContent; // Extract the content

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-29
    • 2012-01-29
    • 1970-01-01
    • 2014-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多