let x = `<div class="wrapper">
<h1>Some title</h1>
<p id="custom_1"></p>
<span id="custom_2"></span>
</div>
<div>other</div>`
let domp = new DOMParser();
let frag = document.createDocumentFragment();
let x_document = domp.parseFromString(x, 'text/html');
let ids = x_document.querySelectorAll("[id]");
let controller = {}
for (let element of ids) {
controller[element.getAttribute('id')] = element;
}
let nb_child = x_document.body.childNodes.length;
let childNodes = x_document.body.childNodes;
for (let i = 0; i < nb_child; i++) {
frag.appendChild(childNodes[0]);
}
let wrapper = document.createElement('div');
wrapper.classList.add('wrapper');
let h1 = document.createElement('h1')
h1.textContent = 'Some title';
let p = document.createElement('p');
let span = document.createElement('span')
let div = document.createElement('div');
div.textContent = 'other';
let frag = document.createDocumentFragment();
wrapper.append(h1,p,span);
frag.append(wrapper, div);
let controller = {
custom_1: p,
custom_2: span
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
DOMParser + querySelectorAll | |
document.createElement |
Test name | Executions per second |
---|---|
DOMParser + querySelectorAll | 12046.6 Ops/sec |
document.createElement | 97692.9 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Purpose
The benchmark compares two approaches to create HTML elements and get references to specific elements with an 'id' attribute:
DOMParser
API to parse an HTML string, creates a fragment, and then uses querySelectorAll
to select elements with an 'id' attribute.createElement
method and builds a controller object by assigning these elements to specific IDs.Options Compared
The two approaches differ in how they create and manipulate the DOM:
querySelectorAll
to select elements with an 'id' attributecreateElement
Pros and Cons of Each Approach
Here are some pros and cons of each approach:
DOMParser + querySelectorAll:
Pros:
Cons:
document.createElement:
Pros:
Cons:
Library Usage
In this benchmark, the following libraries are used:
DOMParser
: A built-in JavaScript API for parsing HTML strings.querySelectorAll
: A method provided by the W3C specification for selecting elements with specific attributes.These libraries provide efficient ways to work with HTML documents and can simplify DOM manipulation.
Special JS Features or Syntax
None of the test cases use any special JavaScript features or syntax beyond what is standard in modern JavaScript development. Both approaches rely on basic DOM manipulation techniques.
Alternatives
If you were to implement this benchmark, you could also explore other approaches, such as:
Keep in mind that each approach has its own trade-offs, and the best choice will depend on your specific requirements and constraints.