问题描述
给出以下HTML:
<div class="date">
<span>
<i class="far fa-user"></i> {Name}
<i class="fas fa-link"></i> LINK
<i class="fas fa-sync-alt"></i> {ReblogSource}
</span>
<span>
<!--irrelevant content-->
</span>
</div>
当<i class="far fa-user"></i> {Name}
可以是任何(数量)纯文本字符时,如何完全删除{Name}
?它出现的<span>
是.date
的第一个孩子(尽管页面上还有<span>
的许多其他实例),而我要删除的字符串是那个的第一个孩子。 。基于Christophe's answer,我认为我可以尝试
var string = '/<i class="far fa-user"></i>.+<i class="fas fa-link"></i>/';
replace(string,'<i class="fas fa-link"></i>');
但是显然这有问题。我...这门语言很不好。
+: {ReblogSource}
也会变成未知长度/内容的纯文本字符串。 <i>
是FontAwesome。我宁愿没有涉及第二个<span>
的答案,尤其是如果它必须包含确切的内容时。
++:我看到两个答案都在代码段中起作用,但是由于某些奇怪的原因,Tumblr不想使其起作用。我已经附上了here结束时的屏幕快照,但是我觉得我需要从这里自行进行故障排除。
解决方法
改为使用DOMParser怎么样?选择范围,然后删除其前三个子节点(两个文本节点和<i>
):
const str = `<div class="date">
<span>
<i class="far fa-user"></i> {Name}
<i class="fas fa-link"></i> LINK
<i class="fas fa-sync-alt"></i> {ReblogSource}
</span>
<span>
<!--irrelevant content-->
</span>
</div>`;
const doc = new DOMParser().parseFromString(str,'text/html');
const span = doc.querySelector('span');
span.childNodes[2].remove(); // text node
span.childNodes[1].remove(); // <i> tag
span.childNodes[0].remove(); // text node
console.log(doc.body.innerHTML);
,
您可以使用包含文本节点和contents()
的{{1}},并在到达each()
时中断
.fa-link
$('.date span:first').contents().each(function() {
const $el = $(this);
if ($el.hasClass('fa-link')) {
return false// breaks each loop
}
$el.remove();
});
console.log($('.date')[0].outerHTML)
如果源html是字符串,只需将其插入一个临时元素中并执行相同的操作
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="date">
<span>
<i class="far fa-user">fa-user</i> {Name}
some extra text
more extra text
<i class="fas fa-link">fa-link</i> LINK
<i class="fas fa-sync-alt">fa-sync-alt</i> {ReblogSource}
</span>
<span>
irrelevant content
</span>
</div>