我有以下代码:
myHtml = '
<div class="outer">
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
<div class="inner"></div>
</div>'
$(myHtml).find('.inner').replaceWith('<h2>hello</h2>')
console.log(myHtml)
我正在尝试用其他一些内容替换我的内部div,但是运行replaceWith后myHtml
不会改变。我怀疑这是因为它不属于DOM树。我对吗?我该如何解决?
谢谢
答案 0 :(得分:1)
//fix the new lines in the string
myHtml = '\
<div class="outer">\
<div class="inner"></div>\
<div class="inner"></div>\
<div class="inner"></div>\
<div class="inner"></div>\
</div>';
//store the changed html back in the string
myHtml = $(myHtml)
.find('.inner')
.replaceWith('<h2>hello</h2>')
//end the find() to go back to the orignal Elements
.end()
//get the new complete html
.prop('outerHTML');
console.log(myHtml)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>