Skip to content

Commit

Permalink
fix: ignore non-sibling elements of nth-of-type
Browse files Browse the repository at this point in the history
refs #52
  • Loading branch information
fczbkk committed Sep 8, 2021
1 parent 0103c29 commit ba9fde1
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
4 changes: 3 additions & 1 deletion src/selector-nth-of-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ export function getElementNthOfTypeSelector (element: Element): CssSelector[] {
const parentElement = element.parentElement

if (parentElement) {
const siblings = Array.from(parentElement.querySelectorAll(tag))
const siblings = Array
.from(parentElement.children)
.filter((element) => element.tagName.toLowerCase() === tag)
const elementIndex = siblings.indexOf(element)
if (elementIndex > -1) {
return [`${tag}:nth-of-type(${elementIndex + 1})`]
Expand Down
18 changes: 17 additions & 1 deletion test/selector-nth-of-type.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('selector - nth-of-type', function () {
it('should not include tag if nthoftype is used', function () {
const result = constructSelector({
tag: ['div'],
nthoftype: ['div:nth-of-type(1)']
nthoftype: ['div:nth-of-type(1)'],
})
assert.equal(result, 'div:nth-of-type(1)')
})
Expand Down Expand Up @@ -81,4 +81,20 @@ describe('selector - nth-of-type', function () {
assert.sameMembers(result, ['span:nth-of-type(1)'])
})

it('should ignore non-sibling elements when constructing', () => {
root.innerHTML = `
<div>
<span></span>
<div>
<span></span>
</div>
<span class="target"></span>
</div>
`
const options = {root, selectors: ['nthoftype']}
const element = root.querySelector('.target')
const result = getCssSelector(element, options)
assert.equal(result, 'span:nth-of-type(2)')
})

})

0 comments on commit ba9fde1

Please sign in to comment.