Skip to content
This repository has been archived by the owner on Dec 14, 2021. It is now read-only.

Add Element.closest #132

Merged
merged 3 commits into from
Jul 24, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions dom.js
Original file line number Diff line number Diff line change
Expand Up @@ -501,6 +501,21 @@
}
}

// Element.closest
// https://developer.mozilla.org/en-US/docs/Web/API/Element/closest
if (window.Element && !Element.prototype.closest) {
Element.prototype.closest = function(s) {
var matches = (this.document || this.ownerDocument).querySelectorAll(s),
i,
el = this;
do {
i = matches.length;
while (--i >= 0 && matches.item(i) !== el) {};
} while ((i < 0) && (el = el.parentElement));
return el;
};
}

function mixin(o, ps) {
if (!o) return;
Object.keys(ps).forEach(function(p) {
Expand Down
7 changes: 7 additions & 0 deletions tests/dom_tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,13 @@ QUnit.test("matches", function(assert) {
assert.ok(document.querySelector('#baz').matches('.beta'));
});

QUnit.test("closest", function(assert) {
assert.equal(document.querySelector('#bar').closest('#foo'), document.querySelector('#foo'));
assert.equal(document.querySelector('#baz').closest('#foo'), document.querySelector('#foo'));
assert.equal(document.querySelector('#foo').closest('#foo'), document.querySelector('#foo'));
assert.notOk(document.querySelector('#baz').closest('#bat'));
});

QUnit.test('Mixin ParentNode: prepend()', function(assert) {
var elem = document.querySelector('#mixin-parentnode');
var orig = elem.innerHTML;
Expand Down