简体   繁体   中英

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?

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM