Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

https://github.com/thiagodp/get-xpath

📑 Extract the XPath from an HTML element
https://github.com/thiagodp/get-xpath

browser deno html javascript node typescript xpath

Last synced: 10 days ago
JSON representation

📑 Extract the XPath from an HTML element

Awesome Lists containing this project

README

        

[![npm (tag)](https://img.shields.io/npm/v/get-xpath?color=green&label=NPM&style=for-the-badge)](https://github.com/thiagodp/get-xpath/releases)
[![Build Status](https://img.shields.io/github/actions/workflow/status/thiagodp/get-xpath/test.yml?style=for-the-badge&color=green)](https://github.com/thiagodp/get-xpath/actions)
[![License](https://img.shields.io/npm/l/get-xpath.svg?style=for-the-badge&color=green)](https://github.com/thiagodp/get-xpath/blob/master/LICENSE.txt)
[![npm](https://img.shields.io/npm/dt/get-xpath?style=for-the-badge&color=green)](https://www.npmjs.com/package/get-xpath)

# get-xpath

> 📑 Extract the XPath of an HTML element

- Works with browsers, [NodeJS](https://nodejs.org/) and [DenoJS](https://deno.land/) (JavaScript 5 and TypeScript)
- No external dependencies
- Unit-tested
- Semantic Versioning

## Install

```bash
npm i get-xpath
```

## API

```typescript
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




const div = document.getElementById( 'x' );
const xpath1 = getXPath( div ); // returns '//*[@id="x"]'
const xpath2 = getXPath( div, { ignoreId: true } ); // returns '/html/body/div'

```

## Usage

**Notes**:
- On [Node](https://nodejs.org/) or [Deno](https://deno.land/), you have to provide a way to accessing or emulating the DOM.
You can use [JSDOM](https://github.com/jsdom/jsdom) (or any other library) for that.
- When using TypeScript, add the value `"dom"` to the property `"lib"`of your `tsconfig.json`. Otherwise you will probably get errors.

### Browser

Global:
```html

<script>
console.log(
getXPath( document.getElementById( 'foo' ) )
);

```

ESM:
```html

import getXPath from 'https://unpkg.com/get-xpath/index.esm.js';
console.log(
getXPath( document.getElementById( 'foo' ) )
);

```

### NodeJS

```javascript
///
const getXPath = require('get-xpath');
console.log(
getXPath( document.getElementById( 'foo' ) )
);
```

### Deno

```typescript
///
import getXPath from 'https://unpkg.com/get-xpath/index.esm.js';
console.log(
getXPath( document.getElementById( 'foo' ) )
);
```

## License

[MIT](LICENSE.txt) © [Thiago Delgado Pinto](https://github.com/thiagodp)