TreeWalker.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. /**
  2. * TreeWalker.js
  3. *
  4. * Copyright, Moxiecode Systems AB
  5. * Released under LGPL License.
  6. *
  7. * License: http://www.tinymce.com/license
  8. * Contributing: http://www.tinymce.com/contributing
  9. */
  10. /**
  11. * TreeWalker class enables you to walk the DOM in a linear manner.
  12. *
  13. * @class tinymce.dom.TreeWalker
  14. */
  15. define("tinymce/dom/TreeWalker", [], function() {
  16. return function(start_node, root_node) {
  17. var node = start_node;
  18. function findSibling(node, start_name, sibling_name, shallow) {
  19. var sibling, parent;
  20. if (node) {
  21. // Walk into nodes if it has a start
  22. if (!shallow && node[start_name]) {
  23. return node[start_name];
  24. }
  25. // Return the sibling if it has one
  26. if (node != root_node) {
  27. sibling = node[sibling_name];
  28. if (sibling) {
  29. return sibling;
  30. }
  31. // Walk up the parents to look for siblings
  32. for (parent = node.parentNode; parent && parent != root_node; parent = parent.parentNode) {
  33. sibling = parent[sibling_name];
  34. if (sibling) {
  35. return sibling;
  36. }
  37. }
  38. }
  39. }
  40. }
  41. /**
  42. * Returns the current node.
  43. *
  44. * @method current
  45. * @return {Node} Current node where the walker is.
  46. */
  47. this.current = function() {
  48. return node;
  49. };
  50. /**
  51. * Walks to the next node in tree.
  52. *
  53. * @method next
  54. * @return {Node} Current node where the walker is after moving to the next node.
  55. */
  56. this.next = function(shallow) {
  57. node = findSibling(node, 'firstChild', 'nextSibling', shallow);
  58. return node;
  59. };
  60. /**
  61. * Walks to the previous node in tree.
  62. *
  63. * @method prev
  64. * @return {Node} Current node where the walker is after moving to the previous node.
  65. */
  66. this.prev = function(shallow) {
  67. node = findSibling(node, 'lastChild', 'previousSibling', shallow);
  68. return node;
  69. };
  70. };
  71. });