javascript cargar un html

What is javascript cargar un html?

Cargar un HTML means loading an HTML page. JavaScript is a programming language that is used to create dynamic web pages. It is also used to make changes to the HTML document, such as adding new elements, changing the content of existing elements, and modifying the style of elements. In this answer, I will explain how to use JavaScript to load an HTML page into another HTML page.

Method 1: Using the XMLHttpRequest object

The XMLHttpRequest object is used to exchange data between the web server and a web page. We can use it to load an HTML page into another HTML page as follows:


var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("myDiv").innerHTML = this.responseText;
  }
};
xhttp.open("GET", "myhtmlpage.html", true);
xhttp.send();
  • The first line creates a new XMLHttpRequest object.
  • The onreadystatechange event is triggered every time the readyState property changes.
  • The if statement checks if the readyState is 4 (request finished and response is ready) and the status is 200 (OK).
  • The getElementById method finds the element with the ID "myDiv".
  • The innerHTML property sets the HTML content of the element to the response text.
  • The open method initializes a new request with the GET method and the URL of the HTML page.
  • The send method sends the request to the server.

Make sure to replace "myhtmlpage.html" with the URL of your HTML page and "myDiv" with the ID of the element where you want to load the HTML page.

Method 2: Using the jQuery load method

jQuery is a JavaScript library that simplifies HTML document traversal and manipulation, event handling, and animation. We can use the load method to load an HTML page into another HTML page as follows:


$(document).ready(function(){
  $("#myDiv").load("myhtmlpage.html");
});
  • The $(document).ready() method specifies a function to be executed when the document is fully loaded.
  • The load method loads data from the server and puts the returned HTML content into the selected element.
  • The parameter of the load method is the URL of the HTML page.
  • The selector "#myDiv" selects the element where you want to load the HTML page.

Make sure to replace "myhtmlpage.html" with the URL of your HTML page and "myDiv" with the ID of the element where you want to load the HTML page.

Conclusion

JavaScript can be used to load an HTML page into another HTML page using the XMLHttpRequest object or the jQuery load method. Both methods are simple and effective, and you can choose the one that suits your needs best.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe