jquery替换
jQuery替换方法
使用.replaceWith()替换元素
replaceWith()方法用于替换DOM元素,接受HTML字符串、DOM元素或jQuery对象作为参数。
$("#oldElement").replaceWith("<div id='newElement'>New content</div>");
使用.replaceAll()反向替换
replaceAll()与replaceWith()功能相同,但语法相反,需将目标元素作为参数传入。
$("<div id='newElement'>New content</div>").replaceAll("#oldElement");
替换HTML内容
若仅需替换元素内部内容,使用.html()方法直接修改HTML。
$("#target").html("<span>Updated content</span>");
替换文本内容
仅替换文本(忽略HTML标签),使用.text()方法。
$("#target").text("Plain text update");
动态替换属性
通过.attr()或.prop()替换元素属性。
$("#image").attr("src", "new-image.jpg"); // 替换src属性
$("#checkbox").prop("checked", true); // 替换布尔属性
链式操作替换
结合其他jQuery方法实现链式调用。

$("#container")
.find(".item")
.replaceWith("<li class='new-item'>Item</li>")
.addClass("updated");
注意事项
- 替换操作会移除原有元素的事件和数据,需手动重新绑定。
- 动态生成的内容需确保选择器能正确匹配新元素。






