Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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)+']' : '')
- }
- // 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();
- }
Add Comment
Please, Sign In to add comment