diff --git a/js/src/dom/selector-engine.js b/js/src/dom/selector-engine.js index d66d8acfc8..c9d25f68cb 100644 --- a/js/src/dom/selector-engine.js +++ b/js/src/dom/selector-engine.js @@ -56,19 +56,17 @@ const SelectorEngine = { }, prev(element, selector) { - const siblings = [] + let previous = element.previousElementSibling - let previous = element.previousSibling - - while (previous && previous.nodeType === Node.ELEMENT_NODE && previous.nodeType !== NODE_TEXT) { + while (previous) { if (this.matches(previous, selector)) { - siblings.push(previous) + return [previous] } - previous = previous.previousSibling + previous = previous.previousElementSibling } - return siblings + return [] } } diff --git a/js/tests/unit/dom/selector-engine.spec.js b/js/tests/unit/dom/selector-engine.spec.js index e13438e6fd..e140c6a3e8 100644 --- a/js/tests/unit/dom/selector-engine.spec.js +++ b/js/tests/unit/dom/selector-engine.spec.js @@ -110,6 +110,21 @@ describe('SelectorEngine', () => { expect(SelectorEngine.prev(btn, '.test')).toEqual([divTest]) }) + + it('should return previous element with comments or text nodes between', () => { + fixtureEl.innerHTML = [ + '
', + '
', + '', + 'Text', + '' + ].join('') + + const btn = fixtureEl.querySelector('.btn') + const divTest = fixtureEl.querySelectorAll('.test')[1] + + expect(SelectorEngine.prev(btn, '.test')).toEqual([divTest]) + }) }) })