条件にあった子孫ノードを集めてくる
ちょっとメモ。
var checker = function (n) { return n && 'INPUT' === n.nodeName && 'text' === n.type; }; var getChildNode = function (root, condFunc) { var result = [ ]; var node = root, n; do { n && (node = n) && (! condFunc || condFunc (n)) && result.push (n); if (n = node.firstChild, ! n) while (n = node.nextSibling, ! n) if (node = node.parentNode, ! node || node == root) return result; } while (node); return result; }; alert(getChildNode(rootNode, checker).length);
gtlt さんに指摘を受けて・・・
配列をレシーバー(?)にして、call する方法には、かなり感動!
評価した戻り値での分岐も感動もの!
しかも、判り易い。
そして、その簡易版。
<!DOCTYPE html> <title></title> <body> <table id="t0" border="1"> <tr><th>a<th>b<th>c <tr><th>1<td><input type="text" name="r001" value="100"><td><input type="text" name="r002" value="200"> <tr><th>2<td><input type="text" name="r003" value="100"><td><input type="text" name="r004" value="200"> </table> <script> function nodeWalk (root, callbackfn) { var node = root.firstChild; var result = [ ]; var dir; var n; while (node) { callbackfn (node) && result.push (node); if ((n = node.firstChild)) { node = n; continue; } do { if (node === root) { node = null; break; } if ((n = node.nextSibling)) { node = n; break; } } while ((node = node.parentNode)); } return result; } function checker (n) { return n && 'INPUT' === n.nodeName && 'text' === n.type; } function setTableInputValue (tableNode, x, y, value) { var cells = nodeWalk (tableNode.rows[y].cells[x], checker); var i = 0, c; while (c = cells[i++]) c.value = value; } setTableInputValue (document.getElementById('t0'), 1, 2, 'Changed !!'); </script>