jQuery Closest vs Closest (v66)

Revision 66 of this benchmark created on


Description

Similar to parent vs closest, only this time testing when searching >1 level of the DOM ancestors.

Preparation HTML

<div>
  <table class="end">
    <tr>
      <td>
        <ul>
          <li>
            1
          </li>
          <li>
            2
          </li>
          <li>
            3
          </li>
          <li>
            4
          </li>
          <li>
            5
          </li>
          <li>
            6
            <ul>
              <li>
                1
              </li>
              <li>
                2
              </li>
              <li>
                2
              </li>
              <li>
                3
                <ul>
                  <li>
                    1
                  </li>
                  <li>
                    2
                  </li>
                  <li>
                    3
                  </li>
                  <li class="start">
                    4
                  </li>
                  <li>
                    5
                  </li>
                </ul>
              </li>
              <li>
                4
              </li>
              <li>
                5
              </li>
            </ul>
          </li>
          <li>
            7
          </li>
          <li>
            8
          </li>
          <li>
            9
          </li>
          <li>
            10
          </li>
        </ul>
      </td>
    </tr>
  </table>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
function Closest (selector, context) {

        var matchedElement = null;
        if (typeof context.closest === 'function') {
            matchedElement = context.closest(selector);
        }
        else {
            // IE is why we can't have nice things
            var matchedElement = context;
            var slicedSelector = selector;
            if (selector.charAt(0) === '.') {
                slicedSelector = selector.slice(1);
            }
            if (!matchedElement.classList.contains(slicedSelector)) {
                while ((matchedElement = matchedElement.parentElement) && !matchedElement.classList.contains(slicedSelector));
            }
            return matchedElement;
        }
        return matchedElement;

    };
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Closest
Closest(".end", $(".start")[0]);
ready
jClosest
$(".start").closest(".end");
ready

Revisions

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