Mike Sav
Mike Sav

Reputation: 15291

Why is parentNode undefined?

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>

Upvotes: 5

Views: 20357

Answers (1)

Martin Tournoij
Martin Tournoij

Reputation: 27822

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.

Upvotes: 9

Related Questions