Skip to content

Commit

Permalink
fix: Allow getElementsByClassName to accept a whitespace-separated list
Browse files Browse the repository at this point in the history
  • Loading branch information
kylehalleman committed Nov 20, 2024
1 parent 7914b54 commit 798c703
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -83,9 +83,14 @@ export default class ParentNodeUtility {
parentNode: Element | DocumentFragment | Document,
className: string
): HTMLCollection<Element> {
const classNames = className
// classNames can be whitespace separated, as many spaces as you want
.split(/\s+/)
.map((className) => `.${className}`)
.join('');
return new HTMLCollection(
PropertySymbol.illegalConstructor,
() => QuerySelector.querySelectorAll(parentNode, `.${className}`)[PropertySymbol.items]
() => QuerySelector.querySelectorAll(parentNode, classNames)[PropertySymbol.items]
);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,32 @@ describe('ParentNodeUtility', () => {
expect(elementByClassName[1]).toBe(element2);
expect(elementByClassName[2]).toBe(element3);
});

it('Supports space-separated class names.', () => {
const addedClassName = 'className otherClassName verySeparatedClassName';
const queriedClassName = 'className otherClassName verySeparatedClassName';

const parent = document.createElement('div');
const element1 = document.createElement('div');
const element2 = document.createElement('div');
const element3 = document.createElement('div');

element1.className = addedClassName;
element2.className = addedClassName;
element3.className = addedClassName;

parent.appendChild(element1);
element1.appendChild(element2);
element1.appendChild(element3);

const elementByClassName = ParentNodeUtility.getElementsByClassName(parent, queriedClassName);

expect(elementByClassName instanceof HTMLCollection).toBe(true);
expect(elementByClassName.length).toBe(3);
expect(elementByClassName[0]).toBe(element1);
expect(elementByClassName[1]).toBe(element2);
expect(elementByClassName[2]).toBe(element3);
});
});

describe('getElementsByTagName()', () => {
Expand Down

0 comments on commit 798c703

Please sign in to comment.