<div></div>
const div = document.createElement('div')
div.innerHTML = 'Hello';
return div.outerHTML;
const frag = document.createRange().createContextualFragment(`<div>Hello</div>`);
const domNode = frag.firstElementChild;
return domNode.outerHTML;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
createElement | |
createContextualFragment |
Test name | Executions per second |
---|---|
createElement | 696793.1 Ops/sec |
createContextualFragment | 147751.2 Ops/sec |
This benchmark on MeasureThat.net compares two ways to create DOM elements in JavaScript:
Method 1: createElement
document.createElement('div')
to create a new <div>
element, then sets its inner HTML to "Hello" and returns the outerHTML of the div.Method 2: createContextualFragment
document.createRange().createContextualFragment(
)
to create a fragment containing the <div>
element with "Hello" inside. It then gets the first child of the fragment and returns its outerHTML.Considerations:
createElement
is significantly faster in this specific case. However, performance can vary depending on factors like browser, complexity of the HTML, and the overall context of your code.createContextualFragment
offers more control over how elements are inserted into the DOM. It's often used in scenarios where you need to build complex structures or manipulate existing content without immediately affecting the visible page.Alternatives:
``
) offer a concise and readable way to embed variables and expressions within strings.Let me know if you have any other questions!