Kaha Kaha - 4 months ago 6
HTML Question

Why innerHTML is not working? (while textContent is working)

I am trying to implement some examples from book and I cannot force this code with innerHTML to work (however textContent is working):

function checkLength(e, minLength) {
var el, elMsg;
if (!e) {
e = window.event();
}
el=e.target || e.srcElement;
elMsg =el.nextSibling;
if (el.value.length<minLength) {
//elMsg.textContent="Username must be " + minLength +" characters or more";
elMsg.innerHTML='Username must be ' + minLength + '' characters or more''; //why are you not working?????
}
}


...

full code is here

UPD. This mistake
"elMsg.innerHTML='Username must be ' + minLength + '' characters or more'';
- was type error, sorry, guys, didn't noticed it

Answer

Your code is fine as I see there are minor mistakes

elMsg.innerHTML='Username must be ' + minLength + '' characters or more''; 

This will genearte the syntax error so replace this with

 elMsg.innerHTML='Username must be ' + minLength + ' characters or more'; 

you are using el.nextSibling that is wrong here you are to use

nextElementSibling so

replace

el.nextSibling

with

  el.nextElementSibling

now one more change

el.nextElementSibling will return next element from your username field, that is br tag in your case. You will have to put a element that has innerHTML propertie. so replace

 <input type="text" id="username"/>
  <br/>

with

 <input type="text" id="username"/>
<span></span>
  <br/>

I hope this will help. If not then let me know and I will create a jsfiddle for you.