JavaScript를 통해 HTML의 요소를 동적으로 변경할 수 있습니다
HTML에 요소 추가
먼저 태그를 생성한 후 해당 콘텐츠를 태그에 추가하고 생성된 태그를 해당 위치에 추가해야 합니다.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>测试文档</title> <script type="text/javascript"> function add(){ var element = document.createElement("p"); var node = document.createTextNode("添加新段落"); element.appendChild(node); x = document.getElementById("demo"); x.appendChild(element); } </script> </head> <body> <div id="demo"> <p>这是第一段</p> </div> <input type="button" value="按钮" onclick="add()" /> </body> </html>
HTML에서 요소 삭제
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>测试文档</title> <script type="text/javascript"> function deleteE(){ var father = document.getElementById("demo"); var child = document.getElementById("p1"); father.removeChild(child); } </script> </head> <body> <div id="demo"> <p id="p1">这是第一段</p> <p id="p2">这是第二段</p> </div> <input type="button" value="删除" onclick="deleteE()" /> </body> </html>