【问题标题】:Password check Cannot read property 'parentNode' of null密码检查无法读取 null 的属性“parentNode”
【发布时间】:2026-02-09 13:35:01
【问题描述】:

因此,如果 2 个给定的密码不匹配,我会尝试使用 Javascript 将 div 插入另一个 div。但是,每次我尝试运行它时,它都会在这篇文章的标题中抛出错误。如果 2 个密码匹配,我只想让 div 消失。

function passwordMismatchError(){
    var pwrd1 = document.getElementById('password').value;
    var pwrd2 = document.getElementById('password-confirmation').value;
    if(pwrd1 != pwrd2){
        // If there is an error box already
        if(document.getElementById("password-mismatch-error")){
            return;
        }
        // If there isn't an error box
        else{
            errcount++;
            var innerdiv = document.createElement('div');
            innerdiv.setAttribute("id", "password-mismatch-error");
            innerdiv.innerHTML = "<p>ERROR: Passwords don't match.</p>";
            (document.getElementById("error-display")).appendChild(innerdiv);
        }
    }
    else{
        // If the passwords match
        errcount--;
        var innerdiv = document.getElementById("password-mismatch-error");
        console.log(innerdiv);
        innerdiv.parentNode.removeChild(innerdiv);
        return;
    }
}

【问题讨论】:

    标签: javascript html css dynamic-programming


    【解决方案1】:

    在您的外部 else 语句中,#password-mismatch-error 永远不会添加到 DOM,因此 innerdiv 将是未定义的。因此您无法访问其parentNode

    要解决此问题,只需在尝试使用 if(document.getElementById("password-mismatch-error")) 删除其父元素之前检查该元素是否存在:

    function passwordMismatchError(){
        var pwrd1 = document.getElementById('password').value;
        var pwrd2 = document.getElementById('password-confirmation').value;
        if(pwrd1 != pwrd2){
            // If there is an error box already
            if(document.getElementById("password-mismatch-error")) {
                return;
            }
            // If there isn't an error box
            else{
                errcount++;
                var innerdiv = document.createElement('div');
                innerdiv.setAttribute("id", "password-mismatch-error");
                innerdiv.innerHTML = "<p>ERROR: Passwords don't match.</p>";
                (document.getElementById("error-display")).appendChild(innerdiv);
            }
        }
        else{
            // If the passwords match
            errcount--;
            // Ensure the error message actually exists in the DOM
            if(document.getElementById("password-mismatch-error")) {
                var innerdiv = document.getElementById("password-mismatch-error");
                console.log(innerdiv);
                innerdiv.parentNode.removeChild(innerdiv);
            }
            return;
        }
    }
    

    希望这会有所帮助! :)

    【讨论】:

    • 我尝试了错误消失的@obsidian-age,但它仍然没有摆脱显示“密码不匹配错误”ID的div。 /:
    最近更新 更多