Home >Web Front-end >JS Tutorial >JavaScript dynamically adds and deletes nodes
In fact, HTML is similar to XML. W3C once wanted to use XML to replace HTML. This means that HTML and XML still have certain common characteristics. Therefore, for XML, we have parsing and dynamic increase or decrease The function of the node, if used in HTML, is to dynamically add some HTML elements such as buttons, hyperlinks, etc. The dynamic effect of such a web page will be better. Let's give a small example to illustrate. This example can dynamically Add some buttons and dynamically delete some buttons. The code is as follows
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>test9.html</title> <script type="text/javascript"> function test(){ //创建元素 var myElement = document.createElement("input");//输入想要创建的类型 myElement.type="button"; myElement.value="我是按钮"; myElement.id="id1"; //将元素添加到指定的节点 document.getElementById("p1").appendChild(myElement); // document.body.appendChild(myElement); } function test1(){ //删除一个元素 // document.getElementById("p1").removeChild(document.getElementById("id1")); //第二种方式灵活 document.getElementById("id1").parentNode.removeChild(document.getElementById("id1")); } </script> </head> <body> <input type="button" onclick="test();" value="动态的创建一个按钮"><br/> <input type="button" onclick="test1();" value="删除按钮"/> <p id="p1" style="width:200px;height: 400px;border: 1px solid red;"> </p> </body> </html>
Here we use most of the methods of document to add and delete nodes. Function, haha, in fact, document is a very powerful Dom object.
Next, write an iteration method for the name of the document to process how to get all the options for the check box and print them out.
The code is as follows
<!sDOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>test8.html</title> <script type="text/javascript"> function test(){ var hobbys = document.getElementsByName("hobby"); for(var i =0; i < hobbys.length; i++){ //判断是否被选择 if(hobbys[i].checked){ window.alert("您的爱好是"+hobbys[i].value); } } } </script> </head> <body> 请选择你的爱好: <input type="checkbox" name="hobby" value="足球"/>足球<br/> <input type="checkbox" name="hobby" value="篮球"/>篮球<br/> <input type="checkbox" name="hobby" value="旅游"/>旅游<br/> <input type="button" value="测试" onclick="test();"> </body> </html>
For more related tutorials, please visit JavaScript Video Tutorial