This article describes the method of dynamically creating and deleting elements in JavaScript. Share it for your reference. The specific analysis is as follows:
In DOM, we can easily and quickly delete dom elements dynamically. Here we will give you a brief introduction.
Example 1:
Create a button dynamically
Copy the code as follows: <html>
<head>
<title>Dynamic Create Button</title>
<script language="javascript">
var a,b,ab,ba,c;
function createInputA(){
a = document.createElement("input"); //Use the DOM's element creation method
a.type = "button" ; //Set the type of element
a.value = "Button A"; //Set the value of the element
a.attachEvent("onclick",addInputB); //Add events for the control
document.body.appendChild(a); //Add control to form
//a = null; //Release the object
}
Example 2:
Copy the code as follows: <html>
<head>
<script type="text/javascript">
function test(){
//createElement() Create an element that specifies the label name [such as: dynamically create a hyperlink]
var createa=document.createElement("a");
createa.id="a1";
createa.innerText="Connect to Baidu";
createa.href="//www.VeVB.COM";
//createa.color="green" ////Add color (don't forget the style attribute, otherwise there will be no effect)
createa.style.color="green"
//Add default location --body and add child nodes
//document.body.appendChild(createa);
//Place the specified location
document.getElementById("div1").appendChild(createa);
}
function test2(){
//Delete the node to removeChild() at the specified location
document.getElementById("div1").removeChild(document.getElementById("a1")); //id name duplicate js to only take the first one
}
</script>
</head>
<body>
<!--Dynamic element creation-->
<input type="button" value="Create a tag" onclick="test()"/><br/>
<input type="button" value="Delete to create a tag" onclick="test2()"/>
<div id="div1">
</div>
</body>
</html>
Dynamically create multiple forms:
Copy the code as follows: <html>
<head>
<script type="text/javascript">
window.onload = function() {
var aBtn = document.createElement("input");
var bBtn = document.createElement("input");
var cBtn = document.createElement("input");
aBtn.type = "button";
aBtn.value = "Button A";
aBtn.onclick = copyBtn;
bBtn.type = "button";
bBtn.value = "Button B";
bBtn.onclick = copyBtn;
cBtn.type = "button";
cBtn.value = "Button C";
cBtn.onclick = clearCopyBtn;
document.body.appendChild(aBtn);
document.body.appendChild(bBtn);
document.body.appendChild(cBtn);
};
function copyBtn() {
var btn = document.createElement("input");
btn.type = "button";
btn.value = this.value;
btn.isCopy = true;
btn.onclick = copyBtn;
document.body.appendChild(btn);
}
function clearCopyBtn() {
var btns = document.getElementsByTagName("input");
var length = btns.length;
for (var i = length - 1; i >= 0; i--) {
if (btns[i].isCopy) {
document.body.removeChild(btns[i]);
}
}
}
</script>
</head>
<body>
</body>
</html>
I hope this article will be helpful to everyone's JavaScript programming.