Skip to content

Commit

Permalink
fix: ensure element has a parent
Browse files Browse the repository at this point in the history
refs #19
  • Loading branch information
fczbkk committed Jun 18, 2020
1 parent 492dbcf commit 95dc8d6
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
12 changes: 8 additions & 4 deletions src/selector-nth-of-type.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,14 @@ import {getTagSelector} from './selector-tag';
*/
export function getNthOfTypeSelector (element) {
const tag = getTagSelector(element)[0];
const siblings = element.parentElement.querySelectorAll(tag);
for (let i = 0; i < siblings.length; i++) {
if (siblings[i] === element) {
return [`${tag}:nth-of-type(${i + 1})`];
const parentElement = element.parentElement;

if (parentElement) {
const siblings = parentElement.querySelectorAll(tag);
for (let i = 0; i < siblings.length; i++) {
if (siblings[i] === element) {
return [`${tag}:nth-of-type(${i + 1})`];
}
}
}

Expand Down
22 changes: 22 additions & 0 deletions test/selector-nth-of-type.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,4 +40,26 @@ describe('selector - nth-of-type', function () {
assert.equal(result, 'p:nth-of-type(2)');
});

it('should not throw for element without parent', function () {
const element = document.createElement('div');
const fn = function () {
getCssSelector(element, {
selectors: ['nthoftype'],
root,
});
};
assert.doesNotThrow(fn);
});

it('should not throw for element directly in document', function () {
const element = document.querySelector('html');
const fn = function () {
getCssSelector(element, {
selectors: ['nthoftype'],
root,
});
};
assert.doesNotThrow(fn);
});

});

0 comments on commit 95dc8d6

Please sign in to comment.