gpt4 book ai didi

javascript - 匹配一个元素并包装匹配元素之前的其他内容

转载 作者:行者123 更新时间:2023-12-04 08:02:45 26 4
gpt4 key购买 nike

我有一个示例数据如下:

<div class="dynamic-data">
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
</div>
我要包装 <span><b>组合在另一个 <div>匹配后的元素 <hr>元素。
任何人都可以建议我如何使用 jQuery .wrap() 来实现它?
预期结果:
<div class="dynamic-data">
<div class="newdiv">
<span>1234 - some text here</span>
<b>1234</b> - some text here
</div>
<div class="newdiv">
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<b>1234</b> - some text here
</div>
<div class="newdiv">
<span>1234 - some text here</span>
<b>1234</b> - some text here
</div>
<div class="newdiv">
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<b>1234</b> - some text here
</div>
</div>

最佳答案

尝试按 <hr> 拆分获取每个<div>的内容,包括文本节点:

$(".dynamic-data > hr").replaceWith("<hr>");
$(".dynamic-data").html("<div class=\"newdiv\">" + $(".dynamic-data").html().split("<hr>").join("</div><div class=\"newdiv\">") + "</div>");
$(".dynamic-data > .newdiv").each(function(index) {
if ($(this).text().trim().length == 0) {
$(this).remove();
};
});
.newdiv {
background-color: lightgreen;
margin:2px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dynamic-data">
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<span>1234 - some text here</span>
<b>1234</b> - some text here
<hr />
</div>

关于javascript - 匹配一个元素并包装匹配元素之前的其他内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66366541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com