Using jQuery XPath selectors
I am using a simple DOM parser function to catch XPath information of all document nodes
For example HTML:
<div>
<div>Everyday People</div>
<div>My name is ACE</div>
<div>Hello world</div>
</div>
Parsing the DOM to store XPath information in an 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 in the script, I use the values stored in arr
to do some functionality like showing, hiding or changing the contents of nodes.
<script>
for(i=0;i<arr.length;i++)
{
//catch the object reference with the XPath info
$(arr[i])
}
</script>
In the above snippet, I am getting an object, but I can’t get a reference to the object so I can use it for something like:
$(arr[i]).text();
Any help would be greatly appreciated. Has anyone worked on jQuery XPath selectors?
a source to share
I'm not really sure if you need Xpaths for anything other than item selection. Because if you don't, you can store the elements 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();
a source to share
The first question that comes to mind is ... Why are you doing this?
Are you generating XPath for an element and storing it in an array so that you can refer to the element later? Why don't you just save the element itself?
What are you trying to do first? Looking at your question and not knowing anything, I suspect there may be easier approaches than yours.
a source to share