function toText()
{
var convertHTML =$('#mainContent').html();
var ele = $(convertHTML + " > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
我的目标是替换下面的内容
<div id="mainContent">
test
<br>
1234
<br>
<span class="underline">test</span>
<br>
<span class="underline">1234</span>
</div>
并希望我的函数输出测试 <br> 1234 <br> test <br> 1234
这就是为什么我不能只使用 text() 因为它带走了 <br>
还有!
最佳答案
像这样尝试:
function toText()
{
var ele = $("#mainContent > span").each(function(){
$(this).replaceWith($(this).text());
});
console.log(ele);
}
你在哪里使用整个 html block 作为 jQuery 选择器:)
关于javascript - 使用 jQuery 替换 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12105813/