Results 1 to 4 of 4

Thread: Ancestor Function

  1. #1
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default Ancestor Function

    I am trying to write an "ancestor function". it will take three values child parent and stop. All three are elements. The purpose is to check whether child is located under parent in the DOM. It should only search until it reachs stop(or the parent).It will then return true or false accordingly. I hope that makes sense. Here's my attempt.
    Code:
    			function ancestor(child,parent,stop){
    				if(child.parentNode){
    					while(child != stop){
    						if(child.parentNode == parent){
    							return true;
    						}
    						else{
    							child = child.parentNode;
    						}
    					}
    				}
    				return false;
    			}
    Unfortunately, I can't get it working. The firefox error console says "child has no properties"(references bolded line). Any help is appreciated as I really need this function to work(I can't think of any other way)

  2. #2
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default

    Never Mind, I figured it out. Here's the working one if you need it
    Code:
    	function ancestor(child,parent,stop){
    				if(child.parentNode){
    					while(child != stop){
    						if(child.parentNode){
    							if(child.parentNode == parent){
    								return true;
    							}
    							else{
    								child = child.parentNode;
    							}
    						}
    						else{
    						return false;
    						}
    					}
    				}
    				return false;
    			}
    If anyone has a better way to do this I would be happy to here it.

  3. #3
    Join Date
    Jun 2005
    Location
    英国
    Posts
    11,876
    Thanks
    1
    Thanked 180 Times in 172 Posts
    Blog Entries
    2

    Default

    Blimey... I've heard of verbosity but that takes the biscuit
    Code:
    function ancestor(child, parent, stop) {
      for(; child.parentNode && child !== stop; child = child.parentNode)
        if(child.parentNode === parent) return true;
      return false;
    }
    Twey | I understand English | 日本語が分かります | mi jimpe fi le jbobau | mi esperanton komprenas | je comprends français | entiendo español | tôi ít hiểu tiếng Việt | ich verstehe ein bisschen Deutsch | beware XHTML | common coding mistakes | tutorials | various stuff | argh PHP!

  4. #4
    Join Date
    Sep 2005
    Posts
    882
    Thanks
    0
    Thanked 3 Times in 3 Posts

    Default

    And that, is why no one should ever trust my advice.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •