Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is parentNode undefined?

Tags:

javascript

dom

I'm trying to write a function that takes an ID then traverses up the DOM to see if that item is a child of a tag. This shouldn't be too hard however my parentNode is coming back as undefined? What am I missing?

Here's a simplified version of my code... thanks in advance.

<!DOCTYPE html>
<html lang="en">
<body>

<div id="top">
    <div id="top2"></div>

    <div id="top3"></div>

    <div id="top4"></div>

    <div id="top5">
        <div id="top5_1"></div>
    </div>
    <div id="top6">
            <div id="top6_1">
                <a href="" id="findMe">here I am...</a>
            </div>
    </div>
</div>

<script>

function findParent(startID, finish){

// change this from id to tag 
start = document.getElementById(startID).tagName;

    while (start.parentNode) {
        start = start.parentNode;

        if (start.tagName === finish){
            console.log("true " + startID + " is a child of " + finish);

        }else{
            console.log("false " + startID + " ISN'T a child of " + finish);
        }

    }
}

findParent("findMe", "BODY");


</script>
</body>
</html>
like image 742
Mike Sav Avatar asked Mar 06 '13 15:03

Mike Sav


People also ask

Why is parentNode null?

Things to note when using the parentNode property: Trying to access the parentNode property on a Document or DocumentFragment nodes returns null - they can never have a parent. The property returns null if the HTML element has been created but not yet attached to the DOM.

What does this parentNode mean?

A Node that is the parent of the current node. The parent of an element is an Element node, a Document node, or a DocumentFragment node.

What is the difference between parentElement and parentNode?

Parent Element returns null if the parent is not an element node, that is the main difference between parentElement and parentNode. In many cases one can use anyone of them, in most cases, they are the same.

What is parentNode in jQuery?

parentNode is native JS, where parent() is not. What you are doing in your code is wrapping the DOM elements in the jQuery object so you can call jQuery specific methods on it. So, you cannot call index() on just this. parentNode, but you can call it on $(this. parentNode).


1 Answers

The problem is:

start = document.getElementById(startID).tagName;

    while (start.parentNode) {
        start = start.parentNode;

You trying to get the parentNode from the tagName, which is a string. Remove the tagName, and you should be fine.

like image 116
Martin Tournoij Avatar answered Oct 22 '22 21:10

Martin Tournoij