document的createElement方法创建具有指定标签的DOM对象

来源:互联网 发布:开拓客户软件 编辑:程序博客网 时间:2024/05/07 11:48
 

可以使用document的createElement方法创建具有指定标签的DOM对象,然后通过调用元素的appentChild的方法将新创建的元素添加到相对应的元素下
<script type="text/javascript">
function showit(){
 var divMain = document.getElementById("divMain"); //获得要添加元素的ID
 var btn = document.createElement("input"); //要添加动态创建的元素
 btn.type= "button";   //要创建的元素的类型
 btn.value = "我是动态创建的1"; //要创建的元素的值
 divMain.appendChild(btn);  //把动态创建的元素添加到指定标签中
 

</script>

HTML代码为
<div id ="divMain"></div>
<input type="button" value="OK" onclick = "showit()" />

---------------------以下为完整代码----------------------------------

<!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=utf-8" />
<title>演示文档</title>
<script type="text/javascript">
function showit(){
 var divMain = document.getElementById("divMain");
 var btn = document.createElement("input");
 btn.type= "button";
 btn.value = "我是动态创建的1";
 divMain.appendChild(btn);
 
}
</script>
</head>
<body>


<div id ="divMain"></div>
<input type="button" value="OK" onclick = "showit()" />
</body>
</html>

 

原创粉丝点击