如何用jQuery删除父元素,而不是其子元素
给定一个HTML文档,任务是删除父元素,但其子元素除外。
步骤 1:
- 使用contents()方法来选择所有的直接子节点,包括所选元素的文本和注释节点。
- 选定的元素被储存在一个变量中。
- 现在,使用replaceWith()方法将父元素的内容替换为其所有的子元素,这些子元素被存储到一个变量中。
例子:这个例子使用contents()和replaceWith()方法来删除父元素,除了其子元素。
<!DOCTYPE HTML>
<html>
<head>
<title>
Remove the parent element not
its child using jQuery
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" id = "h1">
GeeksForGeeks
</h1>
<div id = "parent" style = "border: 1px solid black;">
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<button onclick = "GFG_Fun()">
click here
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
</p>
</div>
<script>
var up = document.getElementById('GFG_UP');
up.innerHTML = "This content is inside a big DIV.";
var down = document.getElementById('GFG_DOWN');
down.innerHTML = "Click on the button to remove "
+ "just this parent DIV";
var heading = document.getElementById('h1');
function GFG_Fun() {
var content = ("#parent").contents();
("#parent").replaceWith(content);
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
方法2:这种方法使用unwrap()方法,将父元素从选定的元素中移除。
示例:
<!DOCTYPE HTML>
<html>
<head>
<title>
Remove the parent element not
its child using jQuery
</title>
<script src =
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style = "text-align:center;">
<h1 style = "color:green;" id = "h1">
GeeksForGeeks
</h1>
<div id = "parent" style = "border: 1px solid black;">
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
This content is inside a big DIV.
</p>
<button onclick = "GFG_Fun()">
click here
<p id = "GFG_DOWN" style =
"color:green; font-size: 20px; font-weight: bold;">
Click on the button to remove just this parent DIV
</p>
</div>
<script>
function GFG_Fun() {
$("#parent").contents().unwrap();
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。