How JS dynamically creates elements

Source: Internet
Author: User

There are three ways to create elements dynamically:

1, document.write ():

A, written in the function, will wash away the previous page elements, so generally do not use or less;

B, open Document.open () or close document.close () document flow;

C, document Flow: The default browser loading order is loaded from the top down, the current page after loading, the equivalent of closing the document flow.

Cases:

<input type= "text" value= "123"/><input type= "button" onclick= "F1 ();" Value= "Dynamically generated elements"/>
<div id= "D" >
<script>
document.write ("789");
</script>
</div>
<script>
document.write ("<input type= ' text ' value= ' 22222 '/>");
Function F1 () {
document.write ("<input type= ' text ' value= ' 8888 '/>");
}
</script>

2, InnerHTML:

A, more convenient, but should pay attention to try not to frequent splicing string;

b, the string has immutability, it is best to put the tag string in the array, saving memory space, improve performance;

C, label. InnerHTML: All child tag elements are obtained and can be used for assignment copies

Innerhtml= "": All Child label nodes will be deleted. Use caution, pay attention to the value of the assignment successively.

Cases:

<input type= "button" value= "Create Element" id= "btn"/>
<div id= "D" ></div>
<script>
var D=document.getelementbyid ("D");
var Btn=document.getelementbyid ("btn");
btn.onclick= function () {
for (Var i=0;i<10;i++) {
d.innerhtml + = "<input type= ' text ' value= ' 8888 ' ><br/>";
}
}

3, Document.createelement:

A, create a pair of tags, is generated in memory;

B, AppendChild () is to cut the in-memory generated label to where it needs to be appended

Cases:

<div id= "D" >
</div>
<script>
var Id=document.getelementbyid ("D");
var ul=document.createelement ("ul");
var li=document.createelement ("Li");

Id.appendchild (UL);
Ul.appendchild (LI);
Li.innerhtml= "added elements";

</script>

How JS dynamically creates elements

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.