密码检查无法读取属性' parentNode'为null

时间:2017-11-07 02:30:29

标签: javascript html css dynamic-programming

所以我尝试使用Javascript将div插入另一个div,如果2个给定的密码不匹配。但是,每次我尝试运行它时,它都会在这篇文章的标题中引发错误。如果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;
    }
}

1 个答案:

答案 0 :(得分:0)

在您的外部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;
    }
}

希望这有帮助! :)