首页 > 解决方案 > 如何使用replaceWith将内容替换为dom

问题描述

我有以下代码:

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,但myHtml在运行 replaceWith 后没有改变。我怀疑这是因为它不是 DOM 树的一部分。我对吗?我该如何解决这个问题?

谢谢

标签: javascriptjqueryhtml

解决方案


//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>


推荐阅读