https://wiki.greasespot.net/api.php?action=feedcontributions&user=Apple&feedformat=atom
GreaseSpot Wiki - User contributions [en]
2024-03-28T19:33:22Z
User contributions
MediaWiki 1.41.0
https://wiki.greasespot.net/index.php?title=XPath_Helper&diff=6839
XPath Helper
2011-12-23T02:32:42Z
<p>Apple: </p>
<hr />
<div>Run a particular [[XPath]] expression <code>p</code> against the context node <code>context</code> (or the document, if not provided) with this overloaded XPath helper.<br />
<br />
Returns the results as an array, unless a value of <code>false</code> is passed in.<br />
<br />
<pre class='sample'><br />
function $x() {<br />
var x='';<br />
var node=document;<br />
var type=0;<br />
var fix=true;<br />
var i=0;<br />
var cur;<br />
<br />
function toArray(xp) {<br />
var final=[], next;<br />
while (next=xp.iterateNext()) {<br />
final.push(next);<br />
}<br />
return final;<br />
}<br />
<br />
while (cur=arguments[i++]) {<br />
switch (typeof cur) {<br />
case "string": x+=(x=='') ? cur : " | " + cur; continue;<br />
case "number": type=cur; continue;<br />
case "object": node=cur; continue;<br />
case "boolean": fix=cur; continue;<br />
}<br />
}<br />
<br />
if (fix) {<br />
if (type==6) type=4;<br />
if (type==7) type=5;<br />
}<br />
<br />
// selection mistake helper<br />
if (!/^\//.test(x)) x="//"+x;<br />
<br />
// context mistake helper<br />
if (node!=document && !/^\./.test(x)) x="."+x;<br />
<br />
var result=document.evaluate(x, node, null, type, null);<br />
if (fix) {<br />
// automatically return special type<br />
switch (type) {<br />
case 1: return result.numberValue;<br />
case 2: return result.stringValue;<br />
case 3: return result.booleanValue;<br />
case 8:<br />
case 9: return result.singleNodeValue;<br />
}<br />
}<br />
<br />
return fix ? toArray(result) : result;<br />
}<br />
</pre><br />
<br />
Example usage:<br />
<br />
<pre class='sample'><br />
var paragraphs = $x("//p", XPathResult.ORDERED_NODE_SNAPSHOT_TYPE), i=1;<br />
paragraphs.forEach(function(paragraph) { // Loop over every paragraph<br />
paragraph.innerHTML = "This is paragraph #"+(i++);<br />
});<br />
</pre><br />
<pre class='sample'><br />
var content=$x("//div[@class='center story']", XPathResult.FIRST_ORDERED_NODE_TYPE);<br />
content.innerHTML="time to eat dinner!";<br />
</pre><br />
<br />
'''Note:''' When you specify a context node, you '''NORMALLY''' need to use a [[XPath#Relative_paths|relative XPath expression]]. However, this function takes care of that technicality.<br />
[http://www.uggbuttonbailey.co.uk ugg bailey button]<br />
[http://www.juicycouture-sale.co.ukĀ Juicy Couture]<br />
[http://www.ghds-outlet.co.uk ghd outlet]<br />
<br />
[[Category:Coding Tips:DOM Access]]</div>
Apple