javascript - 如何使用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 树的一部分。我对吗?我该如何解决这个问题?
谢谢
解决方案
//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>
推荐阅读
- c++ - 使用 OpenGL ES glDrawElements 绘制正方形不起作用
- scala - 从 Uber Jar 中的资源加载 CSV 文件作为数据框
- generics - 在Java中是否可以调用兄弟类的受保护方法,其中兄弟具有不同的类型参数?
- google-apps-script - 即使脚本被授权,安装的触发器也会导致 Browser.inputBox 的权限错误
- javascript - 如何构建一个点击计数但仅显示带有反应组件的奇数的点击器?
- reactjs - React - Chrome 检查器显示正在添加/删除的元素,但更改在浏览器本身中不可见
- javascript - 在每个对象下方创建一个带有弹出窗口的动态列表(在 vue 中)
- unreal-engine4 - 如何在 UE4 中向特定方向发射光线?
- javascript - Appmaker:如何创建和访问全局变量?
- node.js - 使用 JWT Passport 的 NestJS 身份验证不起作用