简体   繁体   中英

error is Cannot read property of appendChild

 function showHelp(id,help) {

 var node = document.createElement('p') ; 
 var text = document .createTextNode('help') ;
 node.appendChild(text) ;
 document.getElementById('id').appendChild(node) ;
 }

 function makeHelpBack(id,help) {

  return function() { showHelp (id,help) ; } ;
  }

  function setUpHelp () {

   var helpText = [{'id':'name' , 'help':'Please fill your full name'} ,
                {'id':'email', 'help':'Email should contain @ '} ] ;

   for (var i = 0 ; i<helpText.length ; i++) {

    var item = helpText[i] ;
    document.getElementById(item.id).onfocus = makeHelpBack(item.id , item.help) ;
    }
    }

    setUpHelp () ;

In this code error message is property of appendChild of null.

Here's how to do it:

 function addHelp(id,help) { var node = document.createElement('span'); var text = document .createTextNode(help) ; node.appendChild(text); node.style.display='none'; insertAfter( document.getElementById(id), node); } function insertAfter(referenceNode, newNode) { return referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } function setUpHelp () { var helpText = [ {'id':'name' , 'help':'Please fill your full name'}, {'id':'email', 'help':'Email should contain @ '} ]; for (var i = 0 ; i<helpText.length ; i++) { addHelp( helpText[i].id, helpText[i].help ); var item = helpText[i] ; document.getElementById(item.id).onfocus = function() { this.nextSibling.style.display='inline' } } } setUpHelp();
 <form> <div> <input id='name'/> </div> <div> <input id='email'/> </div> </form>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM