Reputation: 1849
Suppose, I have a text file like this:
<button onclick="logIn.newTask();">Log In</button>
Now, in Javascript I want to load it in my HTML page with a simply document.appendChild();
like this:
var client = new XMLHttpRequest();
client.open('GET', 'http://localhost/button.txt');
client.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.appendChild(client.responseText); // Load the button see above.
}
}
client.send();
My problem is that this code gives me this error:
So, I try to find how I can traduce text to node but I can not find anything in this subject.
Short question:
I want to load some html's elements in my web page but I can not find any way to achieve this purpose.
Any help is very appreciated.
Tell me if you have some questions or comments.
Upvotes: 1
Views: 4482
Reputation: 48
Why not try it like:
document.appendChild(document.createTextNode(client.responseText));
Keep it short and simple.
Upvotes: 2
Reputation: 887215
You need to create a new DOM node (using document.createElement(tagName)
), then set its innerHTML
to your string of HTML.
This will make the browser parse the HTML into child elements of the new node.
You can then append either the new node or its children to some existing node.
Upvotes: 2