The example in this article describes the implementation method of dynamic creation of javascript elements. Share it with everyone for your reference. The specific analysis is as follows:
document.write can only be created dynamically during page loading
You can call the document's createElement method to create a DOM object with the specified tag, and then add the
by calling the element's appendChild method.
The newly created element is added under the corresponding element
For example:
<html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Dom动态创建元素</title> <script type="text/javascript"> function CreateButton() { var div = document.getElementById("divMain"); var myButton = document.createElement("input"); myButton.type = "button"; myButton.value = "我是动态添加的"; //myButton.id="btn"; 注意:如果设置id的话要避免重复 div.appendChild(myButton); //添加到div上 } </script> </head> <body> <div id="divMain"></div> <input type="button" value="添加元素" onclick="CreateButton()" /> </body> </html>
I hope this article will be helpful to everyone’s JavaScript programming design.