方法:1、利用replaceWith()方法,该方法用于集合中所有匹配的元素,语法为“元素对象.replaceWith(content,function(index))”;2、利用replaceAll()方法,该方法用于把被选元素替换为新的HTML元素,语法为“元素对象.replaceAll(selector)”。

本教程操作环境:windows10系统、jquery3.6.0版本、Dell G3电脑。
1、replaceWith() 方法
$(selector).replaceWith(content,function(index))
content 必需。规定要插入的内容(可包含 HTML 标签)。
可能的值:
HTML 元素
jQuery 对象
DOM 元素
function(index) 可选。规定返回替换内容的函数。
index - 返回集合中元素的 index 位置。
$(DOM).replaceWith(newContent) 用于替换集合中所有匹配的元素,并且返回被删除的元素集合:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script type="text/javascript">
$('document').ready(function (){
$('body>input').click(function (){
$('body>ul>li:gt(1)').replaceWith('<li>替换后的元素</li>')
})
})
</script>
</head>
<body>
<input type="button" value="替换">
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
</ul>
</body>
</html>输出结果:

2、replaceAll() 方法
$(newContent).replaceAll(DOM) 与 $(DOM).replaceWith(newContent) 方法功能一样,只不过是参数位置调换了一下(可以直接在后面赋予样式):
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="jquery.js"></script>
<script type="text/javascript">
$('document').ready(function (){
$('body>input').click(function (){
$('<li>替换后的元素</li>').replaceAll('body>ul>li:gt(1)').css('color','orange');
})
})
</script>
</head>
<body>
<input type="button" value="替换">
<ul>
<li>第一个</li>
<li>第二个</li>
<li>第三个</li>
<li>第四个</li>
</ul>
</body>
</html>输出结果:

视频教程推荐:jQuery视频教程
以上就是jquery怎么替换dom元素的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号