diff --git a/src/__tests__/utils.test.ts b/src/__tests__/utils.test.ts index 098f8d2..c2fe06a 100644 --- a/src/__tests__/utils.test.ts +++ b/src/__tests__/utils.test.ts @@ -111,4 +111,8 @@ test('should getXPathForElement work well', () => { // eslint-disable-next-line max-len `/*[name()='HTML' and namespace-uri()='http://www.w3.org/1999/xhtml']/*[name()='BODY' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='ARTICLE' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3.org/1999/xhtml'][1]/*[name()='DIV' and namespace-uri()='http://www.w3.org/1999/xhtml'][2]`, ); + + const virtualDOM = document.createElement('div'); + const xpath1 = getXPathForElement(virtualDOM, document); + expect(xpath1).toBeUndefined(); }); diff --git a/src/utils.ts b/src/utils.ts index 91603bc..8d3643d 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -142,15 +142,20 @@ export function isEnableScopedCSS(opt: FrameworkConfiguration) { /** * copy from https://developer.mozilla.org/zh-CN/docs/Using_XPath * @param el - * @param xml + * @param document */ -export function getXPathForElement(el: Node, xml: Document) { +export function getXPathForElement(el: Node, document: Document): string | void { + // not support that if el not existed in document yet(such as it not append to document before it mounted) + if (!document.contains(el)) { + return undefined; + } + let xpath = ''; let pos; let tmpEle; let element = el; - while (element !== xml.documentElement) { + while (element !== document.documentElement) { pos = 0; tmpEle = element; while (tmpEle) { @@ -168,7 +173,7 @@ export function getXPathForElement(el: Node, xml: Document) { element = element.parentNode!; } - xpath = `/*[name()='${xml.documentElement.nodeName}' and namespace-uri()='${ + xpath = `/*[name()='${document.documentElement.nodeName}' and namespace-uri()='${ element.namespaceURI === null ? '' : element.namespaceURI }']/${xpath}`; xpath = xpath.replace(/\/$/, '');