Today, I encountered a problem: I used ajax to retrieve the Html of another page. However, I don't want to output these HTML files directly. I want to use getElementsByName to process them before outputting the corresponding content. How can I deal with it with native javascript? Later, a technical group asked about the following code:
The Code is as follows:
Function html2node (s ){
Var d = document. createElement ('P ');
D. innerHTML = s;
If (d. childNodes. length = 1)
Return d. childNodes [0];
Var df = document. createDocumentFragment ();
While (d. firstChild)
Df. appendChild (d. firstChild );
Return df;
}
The general principle is clear. What is confusing is why document. createDocumentFragment is used?
After searching for related resources on the Internet, we found out that document. createDocumentFragment is used to create document fragments.
When we need a large number of appendChild page elements, we can first appendChild these elements into document. createDocumentFragment.
Then, you only need to fragment the appendChild document to the page. In this way, you do not need to refresh the page multiple times to achieve performance optimization. The code above I think it is unnecessary to use document fragments.