JavaScript DOM navigation

Here are a couple of useful functions proposed by John Resig to navigate the DOM:

prev(elem)

function prev(elem) {
  do {
    elem = elem.previousSibling;
  }
  while(elem && elem.nodeType != 1);

  return elem;
}

This function uses an element as its target and then walk back through the element hierarchy.

next(elem)

function next(elem) {
    do {
      elem = elem.nextSibling;
    }

    while(elem && elem.nodeType != 1);
    
    return elem;
}

This function takes an element as its argument and then moves forward through the DOM hierarchy.

first(elem)

function first(elem) {
  elem = elem.firstChild;
  return elem && elem.nodeType != 1 ? next(elem) : elem;
}

This function uses the next() function seen above to move to the first child of a given element.

last(elem)

function last(elem) {
  elem = elem.lastChild;
  return elem && elem.nodeType != 1 ? prev(elem) : elem;
}

This function is similar to the previous one, except for the fact tha uses the prev() function.

parent(elem, num)

function parent(elem, num) {
  num = num || 1;
  for(var i=0; i <num; i++) {
    if(elem != null) {
       elem = elem.parentNode;
    }
   return elem;
  }
}

This function moves back using a number as a reference, provided that the element is not null.

Leave a Reply

Note: Only a member of this blog may post a comment.