17

I am trying to set the innerHTML of one of my elements to the content of another html file that just displays plain text. Is this possible? The way I'm thinking of it is as follows, but obviously it will just set the text to that quote directly instead of displaying the contents of the file.

document.getElementById("myElement").innerHTML = "directory/file.html"
0

2 Answers 2

13

You can do an ajax call to get the files contents and put them in the html on success.

var xhr = typeof XMLHttpRequest != 'undefined' ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
xhr.open('get', 'directory/file.html', true);
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) { 
        document.getElementById("myElement").innerHTML = xhr.responseText;
    } 
}
xhr.send();

Or using jQuery, the load() method is made for you:

$( "#myElement" ).load( "directory/file.html" );
Sign up to request clarification or add additional context in comments.

7 Comments

I suggest you to invert the suggestion order of your answer, since the OP didn't add jQuery in his tags :)
You're right and I did, but the question wasn't even tagged with javascript before I did it... @Buzinas
I haven't learned jQuery or Ajax yet, but it looks like I'm about to. Thanks for the info. Would it just simply not be possible to do in html, or would it just be too much work?
Good, @baao, I haven't seen that he didn't put the javascript tag before. Upvoted your answer! :)
Woah this is faster than a simple innerHTML call I was using to append a template.
|
13

You can use the iframe tag:

<iframe id="myHtml" src="directory/file.html"></iframe>

You can easily change the iframe's content by simply change it's src attribute (it will automatically update):

document.getElementById('myHtml').src = 'other_file.html';

If you also want to use innerHTML to display html from string, you can use the iframe's srcdoc attribute (overrides the src attribute):

document.getElementById('myHtml').srcdoc = '<div><p>Some HTML</p></div>';

2 Comments

while the other answer is technically more correct, this suits my implementation better for the time being, thanks!
Why this answer is technically less-correct than the other answer? I think this one is also concise and does the same thing at the bottom-line. So why should one bother with the ajax or jquery for such a simple task?

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.