The examples in this article describe how JavaScript dynamically creates and deletes elements. Share to everyone for your reference. The specific analysis is as follows:
We can quickly and easily delete and delete DOM elements in the DOM, here we will give you a brief introduction to our friends.
<title> Dynamic Create button </title>
<script language= "JavaScript" >
var a,b,ab,ba,c;
function Createinputa () {
A = document.createelement ("input"); Creating element methods using the DOM
A.type = "button"; To set the type of an element
A.value = "button A"; Set the value of an element
A.attachevent ("onclick", ADDINPUTB); adding events to Controls
Document.body.appendChild (a); Adding controls to a form
A = null; Releasing objects
}
<script type= "Text/javascript" >
function Test () {
CreateElement () Create an element that specifies a label name [for example: Dynamically create a hyperlink]
var createa=document.createelement ("a");
createa.id= "A1";
Createa.innertext= "connected to Baidu";
Createa.href= "Http://www.jb51.net";
Createa.color= "Green"////add color (don't forget style property, otherwise 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 () {
Specify Location Delete node removechild ()
document.getElementById ("Div1"). RemoveChild (document.getElementById ("A1")); ID Duplicate JS only take the first one
}
</script>
<body>
<!--dynamically create elements-->
<input type= "button" value= "Create a label" onclick= "Test ()"/><br/>
<input type= "button" value= "delete Create a label" onclick= "Test2 ()"/>
<div id= "Div1" style= "width:400px;height:300px;border:1px solid silver" >
</div>
</body>
Create multiple forms dynamically:
Copy Code code as follows:
<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>
<body>
</body>
I hope this article will help you with your JavaScript programming.