Is it possible to skip iteration in current subtree and jump to the next node using treewalker? example
<nav>
<p>paragraph</p>
<ul>
<li>one</li>
<li>two</li>
</ul>
<p>paragraph</p>
</nav>
and js
var nav=document.getElementsByTagName("nav")[0];
var tree=document.createTreeWalker(nav,NodeFilter.SHOW_ELEMENT,null,false);
tree.firstChild(); // first paragraph
tree.nextSibling(); // ul
tree.firstChild(); // first li chid of ul
tree.nextNode()||tree.nextSibling() // both return next li
Is there any way how to stop iteration of subtree and jump straight to the another paragraph after treewalker hits first LI element?
Is it possible to skip iteration in current subtree and jump to the next node using treewalker? example
<nav>
<p>paragraph</p>
<ul>
<li>one</li>
<li>two</li>
</ul>
<p>paragraph</p>
</nav>
and js
var nav=document.getElementsByTagName("nav")[0];
var tree=document.createTreeWalker(nav,NodeFilter.SHOW_ELEMENT,null,false);
tree.firstChild(); // first paragraph
tree.nextSibling(); // ul
tree.firstChild(); // first li chid of ul
tree.nextNode()||tree.nextSibling() // both return next li
Is there any way how to stop iteration of subtree and jump straight to the another paragraph after treewalker hits first LI element?
Share Improve this question edited Jun 7, 2015 at 18:19 user663031 asked Jun 7, 2015 at 17:07 DarlynDarlyn 4,93812 gold badges54 silver badges99 bronze badges 2-
Are you asking for
tree.parentNode() && tree.nextSibling()
or are you looking for a way to exclude the children of an<ul>
from the tree entirely? – Bergi Commented Jun 7, 2015 at 17:30 - im asking about excluding the children of an UL entirely – Darlyn Commented Jun 7, 2015 at 17:52
2 Answers
Reset to default 4You can create a custom filter:
var filter = {
acceptNode: function(n) {
return n && n.parentNode && n.parentNode.tagName != "UL"
? NodeFilter.FILTER_ACCEPT
: NodeFilter.FILTER_REJECT;
}
};
var tree=document.createTreeWalker(nav, NodeFilter.SHOW_ELEMENT, filter, false);
If you are on a node such as UL
and want to just skip its children, then you want to try to go in the next sibling direction. But if there's no next sibling, you need to go up another level and try again. (Eventually, you may reach the root of the walker, in which case you need to stop the iteration and return null.)
function nextNodeSkipChildren(tree) {
var node;
while (1) {
if (node = tree.nextSibling()) return node; // return sibling if present
if (!tree.parentNode()) return null; // go up another level and repeat
}
}
If you are already on a child node (such as LI
) and want to skip the rest of the siblings and continue with "uncles" or "great-uncles", then just go back up to the parent before the above:
function nextNodeSkipRemainingSiblings(tree) {
return tree.parentNode() && nextNodeSkipChildren(tree);
}