I'm taking a class on Ajax and this very simple script is throwing an error I don't understand. I keep getting an Uncaught Type Error saying that the appendChild method is not a function.
The function I'm working through is meant to asynchronously load the contents of a text file into a 'p' tag when the link is clicked.
I'm somewhat new to javascript so it's probably something simple I've missed, I'd appreciate any help in understanding what I'm doing wrong.
(function(){
var link = document.getElementsByTagName('a')[0];
link.onclick = function(){
//create xhr object
var xhr = new XMLHttpRequest();
// handle the "onreadystatechange" event
/*
xhr.readysState property values
0 = Uninitialized
1 = Loading
2 = Loaded
3 = Interactive - server is sending a response
4 = Complete
*/
xhr.onreadystatechange = function() {
if ( (xhr.readyState == 4) && (xhr.status == 200 || xhr.status == 304) ) {
xhr.responseText;
var body = document.getElementsByTagName('body')[0];
var p = document.getElementsByTagName('p');
var pText = document.createTextNode(xhr.responseText);
console.log(p);
console.log(pText);
p.appendChild(pText);
body.appendChild(p);
}
};
// open the request
/* arguments:
1. type of request a (GET or POST)
2. path
3. asynchronaus request? (true || false)*/
xhr.open('GET', 'files/ajax.txt', true);
// send the request
xhr.send(null)
return false; // disable default behavior of link
};
})();
I've created a jsFiddle to show my code: http://jsfiddle.net/scottm1164/656edjsf/
getElementsByTagName returns a NodeList. Therefore, you have to access individual items with an index like
var p = document.getElementsByTagName('p')[0];
The reason it was giving you
p.appendChild is not a function
is because appendChild is not a function of type NodeList
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With