Posted By

tylerhall on 11/02/06


Tagged

javascript node DOM functions utility traversal next previous


Versions (?)

Who likes this?

4 people have marked this snippet as a favorite

simpeligent
shachi
vali29
wizard04


DOM Traversal Helper Functions


 / Published in: JavaScript
 

URL: http://developer.mozilla.org/en/docs/Whitespace_in_the_DOM

These functions let you find the next sibling, previous sibling, first child, and last child of a given node (element). What makes them unique is that they safely ignore whitespace nodes so you get the real node you're looking for each time.

  1. function is_all_ws(nod) { return !(/[^\t\n\r ]/.test(nod.data)); }
  2. function is_ignorable(nod) { return (nod.nodeType == 8) || ((nod.nodeType == 3) && is_all_ws(nod)); }
  3. function node_before(sib) {
  4. while ((sib = sib.previousSibling)) {
  5. if (!is_ignorable(sib)) return sib;
  6. }
  7. return null;
  8. }
  9. function node_after(sib) {
  10. while ((sib = sib.nextSibling)) {
  11. if (!is_ignorable(sib)) return sib;
  12. }
  13. return null;
  14. }
  15. function first_child(par) {
  16. var res = par.firstChild;
  17. while(res) {
  18. if(!is_ignorable(res)) return res;
  19. res = res.nextSibling;
  20. }
  21. return null;
  22. }
  23. function last_child(par) {
  24. var res = par.lastChild;
  25. while(res) {
  26. if(!is_ignorable(res)) return res;
  27. res = res.previousSibling;
  28. }
  29. return null;
  30. }

Report this snippet  

You need to login to post a comment.