From: Morgan Harris Date: Tue, 23 Nov 2021 02:12:44 +0000 (+1100) Subject: Return null if `until` not in parent chain X-Git-Tag: 3.1.2~2^2~1 X-Git-Url: https://source.dussan.org/?a=commitdiff_plain;h=e0be375fc57930306999f15c7a7266edb0ba3432;p=svg.js.git Return null if `until` not in parent chain --- diff --git a/spec/spec/elements/Element.js b/spec/spec/elements/Element.js index 5076373..38b862f 100644 --- a/spec/spec/elements/Element.js +++ b/spec/spec/elements/Element.js @@ -188,6 +188,20 @@ describe('Element.js', function () { expect(rect.parents('.foo')).toEqual([ group3 ]) expect(rect.parents('.test:not(.foo)')).toEqual([ group3, group2, group1 ]) }) + + it('returns null if the passed element is not an ancestor', () => { + const canvas = SVG().addTo(container) + const groupA = canvas.group().addClass('test') + const group1 = canvas.group() + const group2 = group1.group() + const group3 = group2.group() + const rect = group3.rect(100, 100) + + + expect(rect.parents('.does-not-exist')).toEqual(null) + expect(rect.parents('.test')).toEqual(null) + expect(rect.parents(groupA)).toEqual(null) + }) }) describe('reference()', () => { diff --git a/src/elements/Element.js b/src/elements/Element.js index a1e7236..2aaeab5 100644 --- a/src/elements/Element.js +++ b/src/elements/Element.js @@ -87,11 +87,8 @@ export default class Element extends Dom { // return array of all ancestors of given type up to the root svg parents (until = this.root()) { - let selector = null - if (typeof until === 'string') { - selector = until - until = this.root() - } else { + const isSelector = typeof until === 'string' + if (!isSelector) { until = makeInstance(until) } const parents = new List() @@ -104,12 +101,16 @@ export default class Element extends Dom { parents.push(parent) - if (parent.node === until.node) { + if (!isSelector && (parent.node === until.node)) { break } - if (selector && parent.matches(selector)) { + if (isSelector && parent.matches(until)) { break } + if (parent.node === this.root().node) { + // We worked our way to the root and didn't match `until` + return null + } } return parents