Home > front end >  What actually happens when a method is the condition of an if statement
What actually happens when a method is the condition of an if statement

Time:03-24

if (username.value.length >= 8) {

       msg.style.background = "green"
       msg.appendChild(validMsg)

       if (msg.appendChild(invalidMsg)) {
       msg.removeChild(invalidMsg)
       }

   }

msg references a div

validMsg and invalidMsg are both text nodes, created via createTextNode

This is being used to add a success message and to remove a warning message on a page, if the warning message is present.

It works without the nested condition, but returns an error ('The node to be removed is not a child of this node')

I have other solutions, but would like to know specifically what happens with the nested if. I know an if can be used to check for JavaScript features, but in the case above, is it actually executing the appendChild method and then removing the child, or just checking if it can appendChild?

A better solution using the approach above would be appreciated also.

CodePudding user response:

It looks like you are trying to message a user if the content of a form input is OK. Here are two examples. On using CSS and the other CSS and JavaScript.

span.invalid, span.valid {
  display: none;
}

input:invalid ~ span.invalid {
  display: inline;
}

input:valid ~ span.valid {
  display: inline;
}
<form name="form01">
  <label>Username: <input type="text" name="username" minlength="8" required/>
    <span >OK</span>
    <span >not OK</span>
  </label>
  <button>Submit</button>
</form>

document.forms.form01.addEventListener('submit', e => {
  e.preventDefault();
  console.log("submit");
});

document.forms.form01.addEventListener('invalid', e => {
  e.preventDefault();
  e.target.parentElement.querySelector('.invalid').classList.add('show');
}, true);

document.forms.form01.addEventListener('input', e => {
  e.target.parentElement.querySelector('.invalid').classList.remove('show');
}, false);
span.invalid {
  display: none;
}

span.show {
  display: inline;
}
<form name="form01">
  <label>Username: <input type="text" name="username" minlength="8" required/>
    <span >not OK</span>
  </label>
  <button>Submit</button>
</form>

CodePudding user response:

Thanks for the replies.

I tested it again and removed the code between the curly braces, namely:

 msg.removeChild(invalidMsg)

This results in both the valid and invalid messages appearing on the page, so

 if (msg.appendChild(invalidMsg))

is adding the invalidMsg. The removeChild method is then taking it away again.

It all works exactly the same if like this:

   if (username.value.length >= 8) {

        msg.style.background = "green"
        msg.appendChild(validMsg)

        msg.appendChild(invalidMsg) 
        msg.removeChild(invalidMsg)
    }
  • Related