How to Load an HTML Page in a Div Using JavaScript

How do I load an HTML page in a div using JavaScript?

I finally found the answer to my problem. The solution is

function load_home() {
document.getElementById("content").innerHTML='<object type="text/html" data="home.html" ></object>';
}

Load html into div without changing the rest of page

You have to write your html code into a <body> </body>

<html> 
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$(function() {
$("#includedContent").load("b.html");
});
</script>
</head>

<body>
<div id="includedContent"></div>
<h1>This is why I rule</h1>
</body>
</html>

I want to load html page in my div tag

This is really a server-sided issue. I've avoided .load(); solely because of the CORs issue it always brings up. I'd glaze over this: Enable CORs

My recommendation, however, is to put all of your html code as strings in a JS file. This isn't as elegant and can be messy, but it's fast and easy to move around thereafter.

var html = '<div id="div-id"><p>Hi there!</p></div>';

$('#target-div').html(html);

That's always how I do things, although you could start to get some ridiculously long strings. You could concatenate them like so so it's easier to read:

var html = 
'<div id="wrapper">' +
'<div id="inner">' +
'<p>Hello!</p>' +
'</div>' +
'</div>';

$('#target-div').html(html);

Not the prettiest thing to look at, but I've written entire full-blown web apps like this, it never presents security issues (namely, CORs) and is blazing fast.

Using this method with multiple servers

Assuming you have a say in what the other server's response will be, you could always do a good ole post request.

var postData = {
optionalData: 1234
};

$.post('https://google.com', postData, function(res) {
$('#target-div').html(res)
});

How can I load a webpage into a div element?

you should use an <iframe> tag as follows:

<div>
<iframe src="http://www.fdsa.com?ID=1">
</div>

or build it programatically:

document.getElementById("content-window").innerHTML='<iframe src="http://www.fdsa.com?ID=1">'

you could use more <iframe> information here:
https://developer.mozilla.org/en/docs/Web/HTML/Element/iframe

enjoy!



Related Topics



Leave a reply



Submit