Dynamically create an element createElement and delete an element
2020-03-30 01:29:19
OfStack
<html>
<script language = "javascript" type = "text/javascript">
function test(){
//Create the element
var myElement = document.createElement("a");//A is the name of the HTML element tag that you want to create
//Add the necessary information to the created element
myElement.href = "http://www.baidu.com";
myElement.innerText = " Connect to baidu ";
myElement.id = "id1";
//myElement.style.top = "300px";
//myElement.style.left = "500px";
//myElement.style.position = "absolute";
//Adds the created element to the body object
//document.body.appendChild(myElement);
//Add the element to div
document.getElementById("div1").appendChild(myElement);
}
function test2(){
//Delete an element
//You can also get the parent of a new element through an attribute
//document.getElementById("id1").parentNode
document.getElementById("div1").removeChild(document.getElementById("id1"));
}
</script>
<body>
<input type = "button" onclick = "test()" value = " Create a hyperlink dynamically "/>
<input type = "button" onclick = "test2()" value = " Dynamically deletes added elements "/>
<div id = "div1" style = "width:200px;height:300px;border:1px solid red">
div1
</div>
</body>
</html>