Skip to content

Instantly share code, notes, and snippets.

@iimos
Last active June 24, 2024 17:05
Show Gist options
  • Select an option

  • Save iimos/e9e96f036a3c174d0bf4 to your computer and use it in GitHub Desktop.

Select an option

Save iimos/e9e96f036a3c174d0bf4 to your computer and use it in GitHub Desktop.

Revisions

  1. iimos revised this gist Jan 20, 2017. 1 changed file with 13 additions and 0 deletions.
    13 changes: 13 additions & 0 deletions xpath.js
    Original file line number Diff line number Diff line change
    @@ -5,3 +5,16 @@ function xpath(el) {
    var sames = [].filter.call(el.parentNode.children, function (x) { return x.tagName == el.tagName })
    return xpath(el.parentNode) + '/' + el.tagName.toLowerCase() + (sames.length > 1 ? '['+([].indexOf.call(sames, el)+1)+']' : '')
    }

    // Usage:

    // Getting xpath for node:
    var xp = xpath(elementNode)

    // Executing xpath:
    var iterator = xpath("//h2")
    var el = iterator.iterateNext();
    while (el) {
    // work with element...
    el = iterator.iterateNext();
    }
  2. iimos revised this gist Sep 17, 2015. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion xpath.js
    Original file line number Diff line number Diff line change
    @@ -4,4 +4,4 @@ function xpath(el) {
    if (el.id) return "//*[@id='" + el.id + "']"
    var sames = [].filter.call(el.parentNode.children, function (x) { return x.tagName == el.tagName })
    return xpath(el.parentNode) + '/' + el.tagName.toLowerCase() + (sames.length > 1 ? '['+([].indexOf.call(sames, el)+1)+']' : '')
    }
    }
  3. iimos created this gist Sep 17, 2015.
    7 changes: 7 additions & 0 deletions xpath.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,7 @@
    function xpath(el) {
    if (typeof el == "string") return document.evaluate(el, document, null, 0, null)
    if (!el || el.nodeType != 1) return ''
    if (el.id) return "//*[@id='" + el.id + "']"
    var sames = [].filter.call(el.parentNode.children, function (x) { return x.tagName == el.tagName })
    return xpath(el.parentNode) + '/' + el.tagName.toLowerCase() + (sames.length > 1 ? '['+([].indexOf.call(sames, el)+1)+']' : '')
    }