5

IDを取得し、DOMをトラバースして、そのアイテムがタグの子であるかどうかを確認する関数を作成しようとしています。これはそれほど難しいことではありませんが、私parentNodeはとして戻ってきundefinedますか?私は何が欠けていますか?

これが私のコードの簡略版です...よろしくお願いします。

<!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>
4

1 に答える 1

9

問題は:

start = document.getElementById(startID).tagName;

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

parentNode文字列であるからを取得しようとしてtagNameいます。を削除するtagNameと、問題ないはずです。

于 2013-03-06T15:33:03.280 に答える