Should I use document.createDocumentFragment or document.createElement

后端 未结 2 991
天涯浪人
天涯浪人 2020-11-28 19:46

I was reading about document fragments and DOM reflow and wondered how document.createDocumentFragment differed from document.createElement as it l

2条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 20:21

    The difference is that a document fragment effectively disappears when you add it to the DOM. What happens is that all the child nodes of the document fragment are inserted at the location in the DOM where you insert the document fragment and the document fragment itself is not inserted. The fragment itself continues to exist but now has no children.

    This allows you to insert multiple nodes into the DOM at the same time:

    var frag = document.createDocumentFragment();
    var textNode = frag.appendChild(document.createTextNode("Some text"));
    var br = frag.appendChild(document.createElement("br"));
    var body = document.body;
    body.appendChild(frag);
    alert(body.lastChild.tagName); // "BR"
    alert(body.lastChild.previousSibling.data); // "Some text"
    alert(frag.hasChildNodes()); // false
    

提交回复
热议问题