Matches vs Closest

JavaScript performance comparison

Test case created by SamBrishes

Preparation code

<div class="level-1">
    <div class="level-2">
        <div class="level-3">
            <div class="level-4">
                <div class="level-5">
                    <div class="level-6">
                        <div class="level-7">
                            <div class="level-8">
                                <div class="level-9"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<div class="level-9-o"></div>
    

Preparation code output

<div class="level-1"> <div class="level-2"> <div class="level-3"> <div class="level-4"> <div class="level-5"> <div class="level-6"> <div class="level-7"> <div class="level-8"> <div class="level-9"></div> </div> </div> </div> </div> </div> </div> </div> </div> <div class="level-9-o"></div>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
.matches()
var match = document.querySelector(".level-9");
while(match && !match.matches(".level-1")){
    match = match.parentElement;
}
pending…
.closest()
document.querySelector(".level-9").closest(".level-1")
pending…
.matches() Polyfil
var customMatches = function(element, selector){
    var matches = (this.document || this.ownerDocument).querySelectorAll(selector), i = matches.length;
    while(--i >= 0 && matches.item(i) !== element){ }
    return i > -1;
}
var match = document.querySelector(".level-9");
while(match && !customMatches(match, ".level-1")){
    match = match.parentElement;
}
pending…
.closest() Polyfill
var customCloses = function(element, selector){
    if(!document.documentElement.contains(element)){
        return null;
    }
    do {
        if(element.matches(selector)){
            return element;
        }
        element = element.parentElement || element.parentNode;
    } while(element !== null && element.nodeType === 1);
    return null;
}
customCloses(document.querySelector(".level-9"), ".level-1")
pending…

You can edit these tests or add even more tests to this page by appending /edit to the URL.

Compare results of other browsers

0 Comments