How would I traverse an XML doc of unknown structure, so as 开发者_StackOverflow社区to perform an operation on every node, using jQuery?
I'm looking for some sort of recursive function whereby I could access each node, check for sub-nodes, and repeat.
What you are looking for is basically a depth-first-search. You could do something like this:
var depthFirstTraversal = function($root, callback) {
$root.children().each(function() {
depthFirstTraversal($(this), callback);
});
callback($root);
};
depthFirstTraversal($(selector), function($node) {
// do stuff with $node
});
Edit: Made a fiddle here
<script>
var xml = "<xml></xml>";
$("#xml").html(xml);
</script>
<div id="xml"></div>
精彩评论