Annibigi
Annibigi

Reputation: 6045

Using jQuery XPath selectors

I'm using a simple DOM parser function to catch XPath information of all nodes of a document

For example, the HTML is:

<div>
  <div>Everyday People</div>
  <div>My name is ACE</div>
  <div>Hello world</div>
</div>

Parsing the DOM to store the XPath info in the array arr:

<script type="text/javascript" src="js/jquery/js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery/js/xpath-selector.js"></script>

<script type="text/javascript">
function get_XPath(elt) 
{
  var path = '';
  for (; elt && elt.nodeType == 1; elt = elt.parentNode)
  {
    var idx = $(elt.parentNode).children(elt.tagName).index(elt) + 1;
    idx > 1 ? (idx='[' + idx + ']') : (idx='');
    path = '/' + elt.tagName.toLowerCase() + idx + path;
  }
  return path;
}

var arr = Array();
htmlDoc = document;
x = htmlDoc.documentElement.childNodes;

for (i=0; i<x.length; i++)
{
  arr.push(get_XPath(x[i]));  
}
</script>

Later on in the script I use the values stored in arr to perform some functions like showing, hiding or changing content of nodes.

<script>
for(i=0;i<arr.length;i++)
{
  //catch the object reference with the XPath info
  $(arr[i])

}
</script>

In the snippet above, I'm getting an object but I'm unable to get the object reference to use it for something like:

$(arr[i]).text();

Any help would be greatly welcome. Anyone worked on jQuery XPath selectors?

Upvotes: 0

Views: 5336

Answers (2)

Tomalak
Tomalak

Reputation: 338158

The first question that comes to mind is... Why are you doing this?

You generate an XPath to an element and store it in an array so you can reference the element later on? Why don't you just store the element itself?

What are you trying to do in the first place? Looking at your question and knowing nothing else, I suspect there might be easier approaches than yours.

Upvotes: 2

Pim Jager
Pim Jager

Reputation: 32119

I'm not quite sure if you need the Xpaths for anything other then selecting the elements. Because if you do not then you could store the elements themself in the arr Array:

var arr = new Array();
htmlDoc = document;
x = htmlDoc.documentElement.childNodes;

for (i=0,b=x.length; i<b; i++){
  arr.push($(x[i]));  
}

Then you could do:

arr[i].text();

Upvotes: 2

Related Questions