Snippets v2

Languages
My Snippets

Search for an element UP the DOM tree Login or Register to Bookmark this snippet

Description Javascript

This function takes an argument (id as string or object reference) and the tag name of an element somewhere up the dom tree. It returns the element, or the body element if the element was not found.

Requires xGetElementById (also available on this site).

The Code Download
  1. function searchUp(elm,findElm) {
  2.     //this function searches the dom tree upwards for the findElm node starting from elm.
  3.     //check if elm is reference
  4.     if(typeof(elm) == 'string') {
  5.         elm = xGetElementById(elm);
  6.     }
  7.     //search up
  8.     //get the parent findElm
  9.     while (elm.nodeName.toLowerCase() != findElm && elm.nodeName.toLowerCase() != 'body')
  10.         elm = elm.parentNode;
  11.     return elm;
  12. }
Credits Contact JC

Added by JC on 11th November, 2007

Comments

There are no comments about this snippet.

Post Comment HTML is allowed

You must be registered and logged in to post a comment.

Login here to post a comment