DOM Element Picker In JavaScript – pick-dom-element

Category: Javascript | October 19, 2023
Author:hmarr
Views Total:160 views
Official Page:Go to website
Last Update:October 19, 2023
License:MIT

Preview:

DOM Element Picker In JavaScript – pick-dom-element

Description:

A JavaScript (TypeScript) based element picker that allows you to pick DOM elements within the document and get the selector path on mouse hover.

How to use it:

1. Install & download the pick-dom-element library.

# NPM
$ npm i pick-dom-element --save

2. Import the pick-dom-element as an ES module.

import { ElementPicker } from "pick-dom-element";

3. Create a new instance of the element picker.

const picker = new ElementPicker();

4. Start the element picker and return the selector path of the selected element.

const status = document.getElementById("status");
picker.start({
  onHover: (el) => {
    const tags = [];
    while (el.parentNode) {
      tags.push(el.tagName);
      el = el.parentNode;
    }
    status.innerText = tags
      .reverse()
      .map((t) => t.toLowerCase())
      .join(" > ");
  };
});

5. Stop the element picker on click.

picker.start({
  onClick: () => {
    picker.stop();
  }
});

6. Apply an element filter function.

picker.start({ onClick: () => { 
  elementFilter: (el) => {
    if (!onlyEmphasis) {
      return true;
    }
    return ['I', 'B'].includes(el.tagName);
  }
}});

7. Run the demo:

$ cd ./pick-dom-element-main/example
$ npm install
$ npm start

Changelog:

v0.2.3 (10/19/2023)

  • Fix margin/padding

v0.2.2 (08/25/2022)

  • Types: make ElementPicker constructor options object optional

v0.2.1 (07/01/2022)

  • Add elementFilter option

v0.2.0 (12/19/2020)

  • Add elementFilter option

You Might Be Interested In:


Leave a Reply