复制代码 代码如下:
<html>
<script language = "javascript" type = "text/javascript">
function test(){
//创建元素
var myElement = document.createElement("a");//a是想创建的html元素标签名
//给创建的元素添加必要的信息
myElement.href = "http://www.baidu.com";
myElement.innerText = "连接到百度";
myElement.id = "id1";
//myElement.style.top = "300px";
//myElement.style.left = "500px";
//myElement.style.position = "absolute";
//把创建的元素添加到body 对象上
//document.body.appendChild(myElement);
//将元素添加到div
document.getElementById("div1").appendChild(myElement);
}
function test2(){
//删除一个元素
//也可以通过属性获得新增元素的父元素
//document.getElementById("id1").parentNode
document.getElementById("div1").removeChild(document.getElementById("id1"));
}
</script>
<body>
<input type = "button" onclick = "test()" value = "动态的创建一个超链接"/>
<input type = "button" onclick = "test2()" value = "动态的删除添加的元素"/>
<div id = "div1" style = "width:200px;height:300px;border:1px solid red">
div1
</div>
</body>
</html>