Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prev() function fails when non-element nodes are present #30117

Merged
merged 8 commits into from
Mar 9, 2020
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
12 changes: 5 additions & 7 deletions js/src/dom/selector-engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
}
}

Expand Down
15 changes: 15 additions & 0 deletions js/tests/unit/dom/selector-engine.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [
'<div class="test"></div>',
'<div class="test"></div>',
'<!-- Comment-->',
'Text',
'<button class="btn"></button>'
].join('')

const btn = fixtureEl.querySelector('.btn')
const divTest = fixtureEl.querySelectorAll('.test')[1]

expect(SelectorEngine.prev(btn, '.test')).toEqual([divTest])
})
})
})