JQuery 课时21 jQuery复制元素、DOM插入到现有元素外
)
复制元素
.clone():创建一个匹配的元素集合的深度拷贝副本
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
</head>
<body>
<p>haha</p>
<p>haha</p>
<p>haha</p>
<span>我是span</span>
<script>
// 克隆一个span放到p标签里
$(function(){
$("span").clone().appendTo($("P"));
})
</script>
</body>
</html>
DOM插入现有元素外
1、.after()
注意是兄弟节点
2、.before()
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
</head>
<body>
<p>haha</p>
<p>haha</p>
<p>haha</p>
<span>我是span</span>
<script>
$(function(){
$("p").before("<span>111</span>");
//$("<span>111</span>").insertBefore($("p"));
})
</script>
</body>
</html>
3、 .insertAfter()
与.after()一样的效果,写法相反
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="./jquery-3.6.0.js"></script>
</head>
<body>
<p>haha</p>
<p>haha</p>
<p>haha</p>
<span>我是span</span>
<script>
$(function(){
//$("p").after("<span>111</span>");
$("<span>111</span>").insertAfter($("p"));
})
</script>
</body>
</html>
4、 .insertBefore()
与.before()一样的效果,写法相反