forked from yaronn/xpath.js
-
Couldn't load subscription status.
- Fork 75
Open
Description
Hello,
I want to use the library to evaluate xPath in shadow DOMs in HTML, but have a problem when I use it with absolute xPath.
Per definition, absolute XPath should look for the target in all of the document, but the document itself does not have access to the content of shadow DOM (which are document-fragment). In my case, the case where we use Shadow DOM as a document and have the absolute xpath only inside it, is enough. Is there a way to achieve it ?
Here is the HTML and Javascript used:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
</head>
<body>
<h1 id="header"></h1>
<div id = 'host'>
</div>
<script src="src/script.js"></script>
</body>
</html>import * as xpath from 'xpath'
const evaluate = (path, node) => {
const xPath = xpath.parse(path)
const options = {
expressionContextNode: node,
isHtml: true,
namespaces: '',
node: node,
}
return xPath.evaluate(options)
}
const host = document.querySelector('#host')
const shadowRoot = host.attachShadow({mode: 'open'})
const target = document.createElement('div')
target.id = 'target'
shadowRoot.appendChild(target)
const nestedTarget = document.createElement('div')
nestedTarget.id = 'nestedTarget'
target.appendChild(nestedTarget)
// Log to console
console.log('host', host)
console.log('shadowRoot', shadowRoot.innerHTML)
console.log('Shadow DOM - relative', evaluate('div', shadowRoot).nodes)
console.log('Shadow DOM - relative nested', evaluate('div/div', shadowRoot).nodes)
console.log('Shadow DOM - absolute', evaluate('//div', shadowRoot).nodes)Metadata
Metadata
Assignees
Labels
No labels

