我正在为这个问题苦苦挣扎。
如何包装新的 <div>
文本周围没有任何类或 ID 的元素?
以下是场景:
<div class="ContentDiv">.....</div>
Share your knowledge. <a href="URL">Be the first to write a review »</a>
我需要新的div
环绕“Share your knowledge. <a href="URL">Be the first to write a review »</a>
”
我尝试过以下方法:
$(document).ready(function() {
$('.ContentDiv').each(function() {
$(this).add($(this).next()).wrapAll('<div class="NewDiv"></div>');
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ContentDiv">.....</div>
Share your knowledge. <a href="URL">Be the first to write a review »</a>
但它不起作用,因为它环绕 <a>
仅元素并将文本保留在其下方。我还需要其中的其余文本。
最佳答案
您需要获取 .ContentDiv
之后的下一个文本节点并将其换行:
$('.ContentDiv').each(function() {
$(this).next('a').add(this.nextSibling).wrapAll('<div class="NewDiv"></div>');
});
由于 jQuery 并未真正获取文本节点,因此 native nextSibling
应该可以工作。
关于javascript - 将新的 div 元素包裹在特定文本周围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14900591/