dcsimg
www.webdeveloper.com
Results 1 to 11 of 11

Thread: JS Error: Uncaught Type: Cannot Read Property RemoveChild of Null

  1. #1
    Join Date
    May 2016
    Posts
    3

    JS Error: Uncaught Type: Cannot Read Property RemoveChild of Null

    Hi all,

    I have created a form that is working beautifully, but serving up an error in the console each time the user backspaces their input field content out and leaves the field empty again.

    Here is my code. Can anyone lend some insight as to what I can do to stop the errors in the console?

    Thanks in advance!

    Robin

    Code:
    var email = document.getElementById("email");
    email.addEventListener('keyup', validateEmail);
    function validateEmail(evt) {    
        var pattern = /^[a-z0-9]+[.]?[a-z0-9]+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; //set the regular expression
        var str = document.getElementById("email").value; //get the user's input
        var emailVal = document.getElementById("emailVal");
        if (emailVal) { //if the error message div is already on the page
            emailVal.parentNode.removeChild(emailVal); //remove it, to prevent a series of error message divs from accumulating
        }
    
            //The next 3 lines appear to be the code in question.
    
    	if (str == "") {//if there is no user input
    		emailVal.parentNode.removeChild(emailVal);//remove the error message
    	}
    
        if (pattern.test(str) === false) { //if the string doesn't match the expression            
            var elem = document.createElement("div"); //create a DIV
            elem.setAttribute("id", "emailVal"); //give it an 1)id, 2)class and 3)message
            elem.setAttribute("class", "form-error-msg");   
            if(window.location.href.indexOf("/en") > -1) {
                elem.innerHTML = 'Invalid email.'; 
            }else{
                elem.innerHTML = 'E-mail inválido'; 
            }            
            email.parentNode.appendChild(elem); //add the div with the current error message
        }	
    } //end function

  2. #2
    Join Date
    Jun 2009
    Location
    Jacksonville, FL U.S.A.
    Posts
    24
    The message appears when the code tries to get the parent of a node that doesn't have one.

    Here's where the node is removed from the DOM.

    Code:
    if (emailVal) {
        emailVal.parentNode.removeChild(emailVal);
    }
    Then the code checks for an empty string and tries to remove the same node a 2nd time.
    The error message appears because the node was already removed and no longer has a
    parent.

    Code:
    if (str == "") {
        emailVal.parentNode.removeChild(emailVal);
    }

  3. #3
    Join Date
    May 2016
    Posts
    3
    Hi Clock Out,

    Thanks so much for your reply! I know why it's happening already, though. I just don't know how to fix it. I have tried removing that exact part of my code, changing it, putting it in a different place, and changing from keyup to key press, but to no avail.

    Do you have any information on how I can stop this from happening?

    Thanks again! I really appreciate your reply!

    Robin

  4. #4
    Join Date
    Jul 2011
    Posts
    211
    //The next 3 lines appear to be the code in question.

    //if (str == "") {//if there is no user input
    // emailVal.parentNode.removeChild(emailVal);//remove the error message
    //}

  5. #5
    Join Date
    May 2016
    Posts
    3
    Hi DaveyErwin,

    I already tried commenting out the code. It caused the error messages to remain on the page at all times, even when the person backed out his code.

    Thanks for the reply, anyway!

  6. #6
    Join Date
    Jun 2009
    Location
    Jacksonville, FL U.S.A.
    Posts
    24
    Check for null in the if statement.

    Code:
    if (str == "" && emailVal.parentNode !== null) {
        emailVal.parentNode.removeChild(emailVal);
    }

  7. #7
    Join Date
    Jul 2011
    Posts
    211
    Please try this ...
    Code:
    <body><input id=email><div id=emailVal>   </div>
    
    <script>
    var email = document.getElementById("email");
    email.addEventListener('keyup', validateEmail);
    function validateEmail(evt) {    
        var pattern = /^[a-z0-9]+[.]?[a-z0-9]+@[a-zA-Z_]+?\.[a-zA-Z]{2,3}$/; //set the regular expression
        var str = document.getElementById("email").value; //get the user's input
        var emailVal = document.getElementById("emailVal");
        if (emailVal) { //if the error message div is already on the page
            emailVal.parentNode.removeChild(emailVal); //remove it, to prevent a series of error message divs from accumulating
        }
        if (pattern.test(str) === false) { //if the string doesn't match the expression            
            var elem = document.createElement("div"); //create a DIV
            elem.setAttribute("id", "emailVal"); //give it an 1)id, 2)class and 3)message
            elem.setAttribute("class", "form-error-msg");   
            if(window.location.href.indexOf("/en") > -1) {
                elem.innerHTML = 'Invalid email.'; 
            }else{
                elem.innerHTML = 'E-mail inválido'; 
            }            
            emailVal=email.parentNode.appendChild(elem); //add the div with the current error message
        }	
    } //end function
    
    
    </script>
    </body>

  8. #8
    Join Date
    Jul 2011
    Posts
    211
    When you remove emailVal
    emailVal still refers to
    the removed element NOT
    the one you just appended
    with the same id so ...
    emailVal=email.parentNode.appendChild(elem);
    sets emailVal as a refference to
    the newly appended element.
    The removed element has no parent.

  9. #9
    Join Date
    Mar 2011
    Posts
    96
    If you don't want to show a message when the input is empty you should do the following.
    Code:
        if (emailVal) { //if the error message div is already on the page
            emailVal.parentNode.removeChild(emailVal); //remove it, to prevent a series of error message divs from accumulating
        }
    
        if (str != '' && pattern.test(str) === false) { //if the string doesn't match the expression

  10. #10
    Join Date
    Oct 2013
    Posts
    1,556
    Unless there's a very compelling reason for doing so, destroying then (re)creating a DIV with its attendant attributes and content on each keystroke seems to me to be a rather inefficient method of displaying a simple "error" message. Consider the following:
    HTML Code:
    <input type="email" name="email">
    <div id="emailVal" class="form-error-msg"></div>
    Code:
    var email = document.querySelector("input[name=email]");
    email.addEventListener('keyup', function() {
        var pattern = /[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$/;
        var str = email.value;
        var emailVal = document.getElementById("emailVal");
        if (pattern.test(str) === false) {
    	if (emailVal.innerHTML == '') { //do only if error does not exist
    	    emailVal.innerHTML = (window.location.href.indexOf("/en") > -1) ? 'Invalid email.' : 'E-mail inválido'; // "shorthand" for if/else
    	}
        }
        else {
    	emailVal.innerHTML = '';
        }
    });
    On a much more basic UX level it's very confusing to have an error message appear when all a user does is type one character in a form field. Even more confusing when s/he can't get rid of it by typing more characters. A better way would be to change the triggering event from a keystroke (keyup, et al) to blur. Let the user get his/her whole email address in there before validating it. In that case either your original script or my script will work, probably with less code in both cases.

    However, if it were my form and in spite of some browser support issues, I'd ditch the script completely and take advantage of HTML 5's input types and other attributes:
    HTML Code:
    <input type="email" name="email" pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,}$" required>
    This is 2016 and people know how to type an email address. Or their browser auto-completes/auto-suggests it for them. All you need to do is catch mistakes on submission which is what this does. An extra bonus is that language doesn't matter -- the "error message" is in the user's default browser language: English, Spanish, Swahili, whatever.
    Last edited by Kevin2; 05-21-2016 at 04:58 PM. Reason: grammar and punctuation
    In dog beers I've only had one.

  11. #11
    Join Date
    Oct 2013
    Posts
    1,556
    In my script above change this line:
    Code:
    if (pattern.test(str) === false) {
    to:
    Code:
    if (str != '' && pattern.test(str) === false) {
    Removes the error when the input is empty.

    Sorry for the late revision...
    In dog beers I've only had one.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles