Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

About this user

Natalie Downe http://natbat.co.uk/

« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS 

Object paternity

// object paternity in Javascript

// relationship of object 1 to object 2
function objectPaternity(obj1, obj2) {
 // given an object this function returns 'child' if obj1 is a child of obj2
 // and 'parent' if obj1 is a parent of obj2 - then 'no' if neither
 var relationship = 'no';
 var currentElement = obj1;
 
 while((typeof currentElement.parentNode != 'undefined') && (currentElement != document.body)) {
  // first cycle through all the parent elements of object 1 to see if object 2 is one of them
  if(currentElement.parentNode == obj2) {
   relationship = 'child';
  }
  // walk up the tree and try again
  currentElement = currentElement.parentNode;
 }
 // if object 1 is not a child of object 2 then we test the other way arround
 if(relationship == 'no') {
  currentElement = obj2;
  while((typeof currentElement.parentNode != 'undefined') && (currentElement != document.body)) {
   // now cycle through all the parent elements of object 2 to see if object 1 is one of them
   if(currentElement.parentNode == obj1) {
    relationship = 'parent';
   }
   // walk up the tree and try again
   currentElement = currentElement.parentNode;
  }
 }
 return relationship;
}
« Newer Snippets
Older Snippets »
Showing 1-1 of 1 total  RSS