Skip to content Skip to sidebar Skip to footer

Using Innerhtml Property To Display Content Of Another Html File?

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

Solution 1:

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

var xhr = typeofXMLHttpRequest != 'undefined' ? newXMLHttpRequest() : newActiveXObject('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" );

Solution 2:

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>';

Post a Comment for "Using Innerhtml Property To Display Content Of Another Html File?"