javascript - How to fix "Uncaught TypeError: Cannot call method 'appendChild' of null" -
i attempting grab text html text area, , phone call create() method when 'submit' button pressed. method trying utilize message text area, , post own p tag class, , post date stamp in own p tag, , own class.
these both in div 'comments'. error getting (using developer tools in chrome), is
uncaught typeerror: cannot phone call method 'appendchild' of null.
this aimed @ "cmt.appendchild(divtag);". new javascript, , practise me increment skills. help appreciated!
var cmt = document.getelementbyid('comments'); function create() { var username = 'user', message = document.getelementbyid("textbox").value, divtag = document.createelement('div'), p1 = document.createelement('p'), p2 = document.createelement('p'); divtag.classname = 'comment'; p1.classname = 'date'; p1.innerhtml = new date(); divtag.appendchild(p1); p2.classname = 'message'; p2.innerhtml = username + ': ' +message; divtag.appendchild(p2); cmt.appendchild(divtag); }
the error getting suggests there no element id "comments" on page. document.getelementbyid
homecoming null
when no element such id found, , cmd.appendchild(divtag)
executed null.appendchild(divtag)
.
if element exists, may executing javascript assigns cmt
variable before element created browser. prevent that, standard practice place <script>
tag includes external javascript just before closing </body>
tag.
if can't move script tag reason, seek running code assigns variable $(document).ready()
(jquery) or equivalent.
javascript append appendchild
No comments:
Post a Comment