Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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, 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"
like image 983
user2789945 Avatar asked Oct 04 '15 20:10

user2789945


People also ask

What is the use of innerHTML property give example?

The innerHTML property can be used to write the dynamic html on the html document. It is used mostly in the web pages to generate the dynamic html such as registration form, comment form, links etc.

What does the innerHTML property do?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .

How do I get data from innerHTML?

How it works. First, get the <ul> element with the id menu using the getElementById() method. Second, create a new <li> element and add it to the <ul> element using the createElement() and appendChild() methods. Third, get the HTML of the <ul> element using the innerHTML property of the <ul> element.


1 Answers

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" );
like image 173
baao Avatar answered Nov 10 '22 07:11

baao