From d2e2e760d6e382f2ca0ed912edba51f8c066c299 Mon Sep 17 00:00:00 2001 From: Kuitos Date: Mon, 12 Oct 2020 18:27:08 +0800 Subject: [PATCH] =?UTF-8?q?=F0=9F=90=9B=20xpath=20return=20undefined=20whi?= =?UTF-8?q?le=20the=20dom=20have=20not=20append=20to=20document=20yet=20(#?= =?UTF-8?q?991)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/__tests__/utils.test.ts | 4 ++++ src/utils.ts | 13 +++++++++---- 2 files changed, 13 insertions(+), 4 deletions(-) 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(/\/$/, '');