Object paternity


/ Published in: Other
Save to your folder(s)



Copy this code and paste it in your HTML
  1.  
  2. // relationship of object 1 to object 2
  3. function objectPaternity(obj1, obj2) {
  4. // given an object this function returns 'child' if obj1 is a child of obj2
  5. // and 'parent' if obj1 is a parent of obj2 - then 'no' if neither
  6. var relationship = 'no';
  7. var currentElement = obj1;
  8.  
  9. while((typeof currentElement.parentNode != 'undefined') && (currentElement != document.body)) {
  10. // first cycle through all the parent elements of object 1 to see if object 2 is one of them
  11. if(currentElement.parentNode == obj2) {
  12. relationship = 'child';
  13. }
  14. // walk up the tree and try again
  15. currentElement = currentElement.parentNode;
  16. }
  17. // if object 1 is not a child of object 2 then we test the other way arround
  18. if(relationship == 'no') {
  19. currentElement = obj2;
  20. while((typeof currentElement.parentNode != 'undefined') && (currentElement != document.body)) {
  21. // now cycle through all the parent elements of object 2 to see if object 1 is one of them
  22. if(currentElement.parentNode == obj1) {
  23. relationship = 'parent';
  24. }
  25. // walk up the tree and try again
  26. currentElement = currentElement.parentNode;
  27. }
  28. }
  29. return relationship;
  30. }
  31.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.