在jQuery中有两个方法可以执行对标签的替换操作,replaceWith()和replaceAll()方法:
replaceWith() :将所有匹配的元素替换成指定的HTML或DOM元素。
replaceAll(selector):用匹配的元素替换掉所有 selector匹配到的元素。
在如下的代码中,首先使用标签选择器获取span,b,i标签,然后调用replaceWith()方法将其替换为h3标签。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<span>123</span>
<b>123</b>
<i>123</i>
<script>
$("span,b,i").replaceWith("<h3>HelloWorld</h3>");
</script>
</body>
</html>
而这段代码中,是使用h3标签调用replaceAll()方法,在参数列表中传入span,b,i标签的jQuery对象。两个程序的运行结果如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<script src="js/jquery-3.3.1.js"></script>
</head>
<body>
<span>123</span>
<b>123</b>
<i>123</i>
<script>
$("<h3>HelloWorld</h3>").replaceAll("span,b,i");
</script>
</body>
</html>