时间:2020-12-16 10:21:38 | 栏目:JavaScript代码 | 点击:次
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>
总结