diff --git a/src/types/YXmlFragment.js b/src/types/YXmlFragment.js index f85b7b62..7fe2267a 100644 --- a/src/types/YXmlFragment.js +++ b/src/types/YXmlFragment.js @@ -32,9 +32,9 @@ import { /** * @typedef {Object} Filters - * @property {CSS_Selector|undefined} Filters.tagname - * @property {ID|undefined} Filters.id - * @property {Record|undefined} Filters.attributes + * @property {CSS_Selector=} Filters.tagname + * @property {ID=} Filters.id + * @property {Record=} Filters.attributes */ /** @@ -188,8 +188,7 @@ export class YXmlFragment extends AbstractType { * Query support: * - tagname * - id - * TODO: - * - attribute + * - attributes * * @param {CSS_Selector|Filters} query The query on the children. * @return {YXmlElement|YXmlText|YXmlHook|null} The first element that matches the query or null. @@ -202,13 +201,17 @@ export class YXmlFragment extends AbstractType { */ let filters = {} - // Allow passing a string to query the tagname for backwards compatability + // Allow passing a string to query the tagname for compatability with DOM api if (typeof query === 'string') { - filters.tagname = query.toUpperCase() + filters.tagname = query } else { filters = query } + if (filters.tagname) { + filters.tagname = filters.tagname.toUpperCase() + } + const iterator = new YXmlTreeWalker(this, element => { // @ts-ignore if (filters.tagname && element.nodeName && element.nodeName.toUpperCase() === filters.tagname) { @@ -231,7 +234,7 @@ export class YXmlFragment extends AbstractType { } // accounts for passing an empty object as a filter - if (keys.length > 1) { + if (keys.length > 0) { return true } } diff --git a/tests/y-xml.tests.js b/tests/y-xml.tests.js index 8c2023fc..f9c63ffc 100644 --- a/tests/y-xml.tests.js +++ b/tests/y-xml.tests.js @@ -64,12 +64,17 @@ export const testTreewalker = tc => { const paragraph2 = new Y.XmlElement('p') const text1 = new Y.XmlText('init') const text2 = new Y.XmlText('text') + paragraph1.setAttribute('custom', '123') paragraph1.insert(0, [text1, text2]) xml0.insert(0, [paragraph1, paragraph2, new Y.XmlElement('img')]) const allParagraphs = xml0.querySelectorAll('p') + const paragraph1ID = paragraph1._item ? paragraph1._item.id : undefined t.assert(allParagraphs.length === 2, 'found exactly two paragraphs') t.assert(allParagraphs[0] === paragraph1, 'querySelectorAll found paragraph1') t.assert(allParagraphs[1] === paragraph2, 'querySelectorAll found paragraph2') - t.assert(xml0.querySelector('p') === paragraph1, 'querySelector found paragraph1') + t.assert(xml0.querySelector('p') === paragraph1, 'querySelector found paragraph1 by string query') + t.assert(xml0.querySelector({ tagname: 'p' }) === paragraph1, 'querySelector found paragraph1 by tagname') + t.assert(xml0.querySelector({ id: paragraph1ID }) === paragraph1, 'querySelector found paragraph1 by id') + t.assert(xml0.querySelector({ attributes: { custom: '123' } }) === paragraph1, 'querySelector found paragraph1 by attribute') compare(users) }