<script
src="https://code.jquery.com/jquery-3.4.1.min.js"
integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
crossorigin="anonymous"></script>
<div id="outer">
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div id="inner">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div id="outer2">
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div>
<div id="inner2">
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
var inner = document.getElementById("inner");
var outer = document.getElementById("outer");
var x = outer.contains(inner)
inner.parentElement === outer
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
contains() method | |
parrentElement() method |
Test name | Executions per second |
---|---|
contains() method | 2324264.5 Ops/sec |
parrentElement() method | 3153161.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
The provided JSON represents a benchmark test created using MeasureThat.net, a website that allows users to create and run JavaScript microbenchmarks. The test is designed to compare two methods: contains()
and parentElement()
. We'll break down what each method does, their pros and cons, and other considerations.
Library: jQuery
The benchmark script includes the jQuery library, which is a popular JavaScript library used for DOM manipulation, event handling, and more. In this test, jQuery is used to manipulate the HTML structure of the document.
Test Cases:
contains()
method:inner
) contains another element (outer
).contains()
method traverses the DOM tree upwards from the containing element until it finds the specified element or reaches the root.parentElement()
method:inner
).nodeName
that doesn't end with a double colon :
, indicating a container element like div
, span
, etc.).Special JS feature: None mentioned in this test case.
Other considerations:
div
elements nested inside each other. This creates a deep DOM tree, which can affect performance.inner
element within an outer
container), so we should expect similar results for both.Alternative approaches:
For similar use cases, you might consider using other DOM manipulation APIs or techniques, such as:
closest()
method: Similar to parentElement()
, but traverses the DOM tree only until it finds a matching element, stopping at the first match.querySelector
/querySelectorAll
: These methods can be used to select elements by their CSS selectors, which can be more efficient than using contains()
or parentElement()
.Keep in mind that the choice of method depends on the specific requirements and constraints of your project.