如何用js创建元素?

JavaScript019

如何用js创建元素?,第1张

var div =document.getElementById('listcont');

var child =div.createElement("div");

child.class="cont"

div. appendChild(child)这样就能把一个子div加进去ID为listcont的div的里面了,其他元素可类似这样添加

var

mask

=

document.createElement("div")//js新建元素

mask.setAttribute("id",

"maskDiv")//给元素加id

mask.onclick

=

hideMask//给元素添加点击事件

var

img

=

document.createElement("img")

img.style.float

=

"right"//js设置样式

img.src

=

"http://520.com/images/download_android.png"

img.style.width

=

"320px"

img.style.float

=

"right"

mask.appendChild(img)

document.body.appendChild(mask)//把元素放进body标签里面

1、先用document.createElement方法创建一个input元素! var newInput = document.createElement("input")

2、设定相关属性,如name,type等

newInput.type=mytype

newInput.name="input1"

3、用appendChild方法,将元素追加到某个标签内容中!

TemO.appendChild(newInput) 

<html >

<head>

<title>动态添加表单元素</title>

</head>

<script language="javascript">

function AddElement(mytype){

var mytype,TemO=document.getElementById("add")

var newInput = document.createElement("input")

newInput.type=mytype

newInput.name="input1"

TemO.appendChild(newInput)

var newline= document.createElement("br")

TemO.appendChild(newline)

}

</script>

<body>

<form action="" method="get" name="frm">

<div id="add">

         <input type="text" name="textfield">

</div>

</form>

<input name="" type="button" value="新建文本框" onClick="AddElement('text')" />

<input name="" type="button" value="新建复选框" onClick="AddElement('checkbox')" />

<input name="" type="button" value="新建单选框" onClick="AddElement('radio')" />

<input name="" type="button" value="新建文件域" onClick="AddElement('file')" />

<input name="" type="button" value="新建密码框" onClick="AddElement('password')" />

<input name="" type="button" value="新建提交按钮" onClick="AddElement('submit')" />

<input name="" type="button" value="新建恢复按钮" onClick="AddElement('reset')" />

</body>

</html>

运行效果: