原生js动态添加新元素、删除元素方法

时间:2021-01-04 09:48:29

1. 添加新元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>动态添加新元素</title>
</head>
<body>
<ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<script>
var child = document.getElementsByClassName("child")[0];
var newChild = document.createElement("li");
var newText = document.createTextNode("wine");
newChild.appendChild(newText);
child.appendChild(newChild)
</script>
</body>
</html>

2.删除已有元素

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>删除元素</title>
<style> </style>
</head>
<body> <ul class="example">
<li class="child">Coffee</li>
<li class="child">Tea</li>
<li class="child">Coffee</li>
<li class="child">Tea</li>
</ul>
<script>
var parent = document.querySelectorAll(".example")[0];
var child = document.querySelectorAll(".child")[2];
document.writeln(child.innerHTML)
parent.removeChild(child); //第二种方法此行替换:child.parentNode.removeChild(child);
</script>
</body>
</html>