jQuery中替换DOM节点常用方法如下:
1、replaceWith():将所有匹配的元素替换成指定的HTML或DOM元素。
实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-3.3.1.js"></script>
</head>
<body>
<span>Hello</span>
<b>Hello</b>
<i>Hello</i>
<script>
$("span,b,i").replaceWith("<h3>World</h3>");
</script>
</body>
</html>
2、replaceAll():用匹配的元素替换掉所有selector匹配到的元素。
实例如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="../js/jquery-3.3.1.js"></script>
</head>
<body>
<span>Hello</span>
<b>Hello</b>
<i>Hello</i>
<script>
$("<h3>World</h3>").replaceAll("span,i,b");
</script>
</body>
</html>
注意:替换前,已绑定时间的元素,替换后原先事件会与元素一起消失。