<div id='div1'>
<div id='div2'>
<div id='div3'>
</div>
</div>
</div>
var box = document.getElementById('div1');
var clicked = document.getElementById('div3');
const isClickInside = box.contains(clicked);
return isClickInside;
const isClickInside = clicked.closest('#div1');
return isClickInside;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
contains | |
closest |
Test name | Executions per second |
---|---|
contains | 5965861.0 Ops/sec |
closest | 6216445.5 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what's being tested.
Benchmark Definition:
The website measures the performance of two methods: contains()
and closest()
. The contains()
method checks if an element is contained within another element, while closest()
finds the closest ancestor element that matches a specified selector.
Script Preparation Code:
var box = document.getElementById('div1');
var clicked = document.getElementById('div3');
This code retrieves two elements from the HTML page using their IDs: box
(the outermost container) and clicked
(a child element within box
).
Html Preparation Code:
<div id='div1'>
<div id='div2'>
<div id='div3'>
</div>
</div>
</div>
This HTML code defines the structure of the page, where div1
is the outermost container, and div3
is a child element within it.
Individual Test Cases:
There are two test cases:
const isClickInside = box.contains(clicked);
return isClickInside;
This code checks if clicked
(the innermost element) is contained within box
(the outermost container). The contains()
method returns a boolean value indicating whether the element is found.
const isClickInside = clicked.closest('#div1');
return isClickInside;
This code uses the closest()
method to find the closest ancestor element that matches the selector #div1
. Since div3
is already inside div1
, this method will return a reference to itself. The result is then returned.
Pros and Cons:
closest()
due to the overhead of checking each element in the DOM treecontains()
Library:
The closest()
method uses the Web Content Accessibility Guidelines (WCAG) 2.1 specification, which defines an API for finding the closest ancestor element that matches a specified selector.
Special JS Feature/Syntax:
None mentioned in this benchmark definition.
Other Alternatives:
If you need to check if an element is contained within another, you can use:
contains()
with the Element.contains()
method (Chrome 114)closest()
with a more specific selector (e.g., closest('#div1')
)Keep in mind that the performance difference between these methods may vary depending on your specific use case and the browser being used.