๐ Extract the XPath of an HTML element
- Works with browsers, NodeJS and DenoJS (JavaScript 5 and TypeScript)
- No external dependencies
- Unit-tested
- Semantic Versioning
npm i get-xpath
function getXPath( element: HTMLElement, options?: Partial< Options > ): string;
Where options
is an optional object containing:
name | type | description |
---|---|---|
ignoreId |
boolean | Do not take elements' ID into account |
Example:
<html>
<body>
<div id="x" ></div>
<script>
const div = document.getElementById( 'x' );
const xpath1 = getXPath( div ); // returns '//*[@id="x"]'
const xpath2 = getXPath( div, { ignoreId: true } ); // returns '/html/body/div'
</script>
</body>
</html>
Notes:
- On Node or Deno, you have to provide a way to accessing or emulating the DOM. You can use JSDOM (or any other library) for that.
- When using TypeScript, add the value
"dom"
to the property"lib"
of yourtsconfig.json
. Otherwise you will probably get errors.
Global:
<script crossorigin src="https://unpkg.com/get-xpath" >
<script>
console.log(
getXPath( document.getElementById( 'foo' ) )
);
</script>
ESM:
<script type="module" >
import getXPath from 'https://unpkg.com/get-xpath/index.esm.js';
console.log(
getXPath( document.getElementById( 'foo' ) )
);
</script>
/// <reference lib="dom" />
const getXPath = require('get-xpath');
console.log(
getXPath( document.getElementById( 'foo' ) )
);
/// <reference lib="dom" />
import getXPath from 'https://unpkg.com/get-xpath/index.esm.js';
console.log(
getXPath( document.getElementById( 'foo' ) )
);