I have the following code that pretty much creates a div element and whatever is inside and puts it into
function create(htmlStr) {
var frag = document.createDocumentFragment(), temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
var fragment = create('<div id="test">HELLO</div>');
document.body.insertBefore(fragment, document.body.childNodes[0]);
-
I am, however, confused as to why do we create another
divtemp = document.createElement('div');
If we are already passing<div id="test">HELLO</div>tocreate()function. Seems to me that would create a div within a div (but it doesn’t). Or does that just get extracted withtemp.firtChild? -
What does
temp.innerHTML = htmlStr;do sincetempis adiv?
To answer your 1st question, it basically creates a parent div to contain the
htmlStr, which happens to be<div id="test">HELLO</div>. So basically, this line of code by itself simply generates a div, but thistempdiv is then used to contain thehtmlStras a child. But you are right; thetempdiv is simply extracted later; it’s pretty much useless. I don’t know why that’s there if there is no other code to consider.As for question 2, all it does is make the
htmlStra child of the created div. In effect, this code makestemp.innerHTML == htmlStr == temp.firstChild. It’s kinda redundant.Basically, your code makes the following HTML: