1

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:

enter image description here

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.

1
  • You don't actually want to append it directly to the document, outside </body>. Commented Oct 24, 2017 at 17:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

Why not try it like:

document.appendChild(document.createTextNode(client.responseText));

Keep it short and simple.

4 Comments

He probably wants it to be parsed as HTML.
or maybe it's just text
@Slaks, what are the differences?
@S.P.H.I.N.X: Learn about XSS vulnerabilities and escaping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.