Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
getElementByXPath | Get DOM-Nodes by its XPath.
function (
a, // the XPath
b // document-placeholder
) {
b = document;
return b.evaluate(
a, // xpathExpression
b, // contextNode
null, // namespaceResolver
9, // resultType
null // result
).singleNodeValue; // the first node
}
function(a,b){b=document;return b.evaluate(a,b,null,9,null).singleNodeValue}
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2013 Yannick Albert <http://yckart.com>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
{
"name": "getElementByXPath",
"description": "Get DOM-Nodes by its XPath.",
"keywords": [
"selector",
"xpath",
"path",
"node",
"dom"
]
}
<!DOCTYPE html>
<title>getElementByXPath | Get DOM-Nodes by its XPath.</title>
<div>Expected value: <b>140byt.es</b></div>
<div>Actual value: <b id="ret"></b></div>
<script>
var getElementByXPath = function(a,b){b=document;return b.evaluate(a,b,null,9,null).singleNodeValue}
var path = '//html[1]/body[1]/div[1]/b[1]';
document.getElementById('ret').innerHTML = getElementByXPath(path).innerHTML;
</script>
@atk

This comment has been minimized.

Copy link

@atk atk commented Aug 28, 2013

You could save a lot of space by using 9 instead of XPathResult.FIRST_ORDERED_NODE_TYPE.

@yckart

This comment has been minimized.

Copy link
Owner Author

@yckart yckart commented Aug 29, 2013

@atk Uff, good point!

@kthy

This comment has been minimized.

Copy link

@kthy kthy commented Apr 23, 2014

Er, no - bad point! Using magic numbers instead of named constants is evil.

@yckart

This comment has been minimized.

Copy link
Owner Author

@yckart yckart commented Jun 4, 2014

@kthy Sure, in the wildnis I would not use magic numbers like this, but this is a gist for 140byt.es, so I think it is "reasonable".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment