Adding a full html to a div
How about, I'm trying to add an html file to a Div
<!DOCTYPE html>
<html lang="en">
<head>
<title>Inicio</title>
</head>
<body>
<div> <!-- este div donde agregare un html-->
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
</body>
</html>
Where I will add another html with another content dipo (with tables for example)
What would be the right way to do it?
4 answers
You have to do it with a <iframe>
Example:
<iframe id="Example2"
name="Example2"
title="Example2"
width="400"
height="300"
frameborder="0"
scrolling="no"
marginheight="0"
marginwidth="0"
src="https://maps.google.com/maps?f=q&source=s_q&hl=es-419&geocode=&q=buenos+aires&sll=37.0625,-95.677068&sspn=38.638819,80.859375&t=h&ie=UTF8&hq=&hnear=Buenos+Aires,+Argentina&z=11&ll=-34.603723,-58.381593&output=embed">
</iframe>
You can use Javascript:
<script>
document.getElementById("demo").innerHTML = "Hello <b>world</b>!";
</script>
Or JQuery
$("button").click(function(){
$("#demo").html("Hello <b>world</b>!");
});
You just need something that fires that event, for example a click and you can change it every time the event is executed. Your div should have the ID "demo"
<div id="demo">
...
</div>
You can also do this with php using include:
<div id="demo">
<?php
include("ruta_del_html.htmlophp");
?>
</div>
I hope it serves you.
You can use AJAX to read the contents of the other HTML file and write it to your page:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("ID_OBJETIVO").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "URL_DEL_HTML_QUE_QUIERES_LEER", true);
xmlhttp.send();
Or if you use a library like jQuery, you can do something even simpler with functions like $.ajax () or $.get():
$.ajax({
type: "GET",
url: "URL_DEL_HTML_QUE_QUIERES_LEER",
success: function(datos) {
$("#ID_OBJETIVO").html(datos);
}
})
If the content is a Web page like GoogleMaps, as eduardo says, you should use an iframe (which is no longer recommended). Otherwise, if the Html code is inside your site, or is a partrialView you can do it using Jquery.
function insertHtml(){
$("#htmlins").html("<span>este codigo html fue insertado</span>")
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlins">
</div>
<input type="button" value="Insertar Html" onclick="insertHtml()"/>