Skip to content
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
8 changes: 7 additions & 1 deletion web_src/js/utils/dom.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {createElementFromAttrs, createElementFromHTML, querySingleVisibleElem} from './dom.ts';
import {createElementFromAttrs, createElementFromHTML, queryElemChildren, querySingleVisibleElem} from './dom.ts';

test('createElementFromHTML', () => {
expect(createElementFromHTML('<a>foo<span>bar</span></a>').outerHTML).toEqual('<a>foo<span>bar</span></a>');
Expand Down Expand Up @@ -26,3 +26,9 @@ test('querySingleVisibleElem', () => {
el = createElementFromHTML('<div><span>foo</span><span>bar</span></div>');
expect(() => querySingleVisibleElem(el, 'span')).toThrowError('Expected exactly one visible element');
});

test('queryElemChildren', () => {
const el = createElementFromHTML('<div><span class="a">a</span><span class="b">b</span></div>');
const children = queryElemChildren(el, '.a');
expect(children.length).toEqual(1);
});
5 changes: 5 additions & 0 deletions web_src/js/utils/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,11 @@ export function queryElemSiblings<T extends Element>(el: Element, selector = '*'

// it works like jQuery.children: only the direct children are selected
export function queryElemChildren<T extends Element>(parent: Element | ParentNode, selector = '*', fn?: ElementsCallback<T>): ArrayLikeIterable<T> {
if (window.vitest) {
// bypass the vitest bug: it doesn't support ":scope >"
const selected = Array.from<T>(parent.children as any).filter((child) => child.matches(selector));
return applyElemsCallback<T>(selected, fn);
}
return applyElemsCallback<T>(parent.querySelectorAll(`:scope > ${selector}`), fn);
}

Expand Down