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

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>

 

posted @ 2019-05-04 18:52  给时光以生命  阅读(3576)  评论(0编辑  收藏  举报