LoginSignup
0
0

More than 3 years have passed since last update.

documentとHTMLElementにgetElementByXPath定義する

Posted at

ブラウザのコンソールでのちょっとした作業用。探せば色々見つかるのだけど、 documentに対してだけではなく、どのHTMLElementに対しても実行できるところまでまとまってるのはあまりないようだったので。

(() => {

  const __getElementByXPath = function(path, root) {
    const result = document.evaluate(path, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null)
    return result.snapshotLength > 0 ? result.snapshotItem(0) : null
  }
  const __getElementsByXPath = function(path, root) {
    const array = []
    const result = document.evaluate(path, root, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    for (let i = 0; i < result.snapshotLength; i++) {
      array.push(result.snapshotItem(i));
    }
    return array;
  }

  document.getElementByXPath = function(path) {
    return __getElementByXPath(path, this)
  }
  document.getElementsByXPath = function(path) {
    return __getElementsByXPath(path, this)
  }
  HTMLElement.prototype.getElementByXPath = function(path) {
    return __getElementByXPath(path, this)
  }
  HTMLElement.prototype.getElementsByXPath = function(path) {
    return __getElementsByXPath(path, this)
  }

})()
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0