I need to get an XPathResult with javascript and iterate through it, cloning each node of the result. Initially, I tried the following with the result as ORDERED_NODE_ITERATOR_TYPE:
childNodesXPath = '//div[@id="'+subcat_id+'" and @parentid="'+subcat_parent_id+'"]';
subcat_child_nodes = document.evaluate(childNodesXPath, document, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);
while (next_child_node = subcat_child_nodes.iterateNext()) {
new_child_node = next_child_node.cloneNode(true);
new_child_node.setAttribute('parentid', target_id);
new_child_node.setAttribute('grandparentid', target_parentid);
new_length = new_subcat_child_nodes.push(new_child_node);
}
Of course I discovered that the iterator became invalid as soon as the first node was cloned because the DOM changed, so then I tried this with the result as ORDERED_NODE_SNAPSHOT_TYPE:
childNodesXPath = '//div[@id="'+subcat_id+'" and @parentid="'+subcat_parent_id+'"]';
subcat_child_nodes = document.evaluate(childNodesXPath, document, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
for (i=0; i<subcat_child_nodes.length; i++) {
new_child_node = subcat_child_nodes[i].cloneNode(true);
new_child_node.setAttribute('parentid', target_id);
new_child_node.setAttribute('grandparentid', target_parentid);
new_length = new_subcat_child_nodes.push(new_child_node);
}
This did not work because there is no length property for the XPathResult object. I also tried subcat_child_nodes.forEach() and that did not work, nor does iterateNext().
How do I iterate through an XPathResult that is of type ORDERED_NODE_SNAPSHOT_TYPE in a way that allows me to clone each node? If that is not possible, is there a way to clone an entire XPathResult that is a list of nodes?
.snapshotLength
and.snapshotItem()
- which you can use to create an array if you like:const array = Array.from({length: subcat_child_nodes .snapshotLength}, (_, i) => subcat_child_nodes.snapshotItem(i));