How to Get HTML From URL in JavaScript

Harshit Jindal Mar 11, 2025 JavaScript
  1. Using the Fetch API
  2. Using XMLHttpRequest
  3. Using jQuery
  4. Conclusion
  5. FAQ
How to Get HTML From URL in JavaScript

In the world of web development, fetching HTML content from a URL is a common task. Whether you’re building a web scraper, creating dynamic web applications, or just experimenting with APIs, knowing how to retrieve HTML using JavaScript is essential.

In this tutorial, we will explore various methods to get HTML code from a URL using JavaScript. We will cover the Fetch API, XMLHttpRequest, and jQuery, providing you with clear examples and explanations. By the end of this guide, you’ll have a solid understanding of how to pull HTML content from any accessible URL and utilize it in your projects. Let’s dive in!

Using the Fetch API

The Fetch API is a modern way to make network requests in JavaScript. It’s promise-based, which means it allows you to work with asynchronous code more easily. Here’s how you can use the Fetch API to get HTML from a URL.

fetch('https://example.com')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.text();
  })
  .then(html => {
    console.log(html);
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });

The code above initiates a GET request to the specified URL. The fetch function returns a promise that resolves to the response object. We check if the response is okay; if not, we throw an error. If the response is valid, we call response.text() to extract the HTML content, which is then logged to the console. The catch block handles any errors that may occur during the fetch operation, ensuring that you have a robust error-handling mechanism in place.

Output:

<!DOCTYPE html>
<html>
<head>
    <title>Example Domain</title>
</head>
<body>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents.</p>
</body>
</html>

Using the Fetch API is ideal for modern web applications because it supports promises and is more flexible than older methods. It’s also widely supported in modern browsers, making it a preferred choice for developers.

Using XMLHttpRequest

Before the Fetch API became popular, XMLHttpRequest was the primary way to make HTTP requests in JavaScript. While it’s a bit more verbose than the Fetch API, it’s still a valid method to retrieve HTML from a URL.

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com', true);
xhr.onload = function () {
  if (xhr.status >= 200 && xhr.status < 300) {
    console.log(xhr.responseText);
  } else {
    console.error('Request failed with status:', xhr.status);
  }
};
xhr.onerror = function () {
  console.error('Request failed');
};
xhr.send();

In this code snippet, we create a new instance of XMLHttpRequest and configure it to make a GET request to the specified URL. The onload event is triggered when the request completes successfully. If the status code indicates success (200-299), we log the response text, which contains the HTML content. If the request fails, we log an error message. The onerror event handles network errors.

Output:

<!DOCTYPE html>
<html>
<head>
    <title>Example Domain</title>
</head>
<body>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents.</p>
</body>
</html>

While XMLHttpRequest may seem outdated compared to the Fetch API, it is still widely used in legacy codebases. Understanding how it works can be beneficial when maintaining older applications or when you need to support older browsers that do not support the Fetch API.

Using jQuery

If you’re already using jQuery in your project, you can take advantage of its $.ajax() method to fetch HTML from a URL easily. jQuery simplifies the syntax and provides a more concise way to handle AJAX requests.

$.ajax({
  url: 'https://example.com',
  method: 'GET',
  success: function(data) {
    console.log(data);
  },
  error: function(xhr, status, error) {
    console.error('Error occurred:', status, error);
  }
});

In this example, we use jQuery’s $.ajax() method to initiate a GET request. The success callback function is executed if the request is successful, logging the retrieved HTML content. The error callback handles any issues that arise during the request, providing useful feedback for debugging.

Output:

<!DOCTYPE html>
<html>
<head>
    <title>Example Domain</title>
</head>
<body>
    <h1>Example Domain</h1>
    <p>This domain is for use in illustrative examples in documents.</p>
</body>
</html>

Using jQuery for AJAX requests is particularly useful for developers who prefer a simpler syntax and want to handle cross-browser compatibility issues seamlessly. However, it’s important to note that jQuery adds additional overhead to your project, so consider whether you need the library for other functionalities before including it.

Conclusion

In this tutorial, we explored three different methods to get HTML from a URL using JavaScript: the Fetch API, XMLHttpRequest, and jQuery. Each method has its own advantages and use cases, allowing developers to choose based on their project requirements and browser compatibility needs. The Fetch API is the most modern and flexible option, while XMLHttpRequest remains relevant for older applications. jQuery provides a simplified approach for those already using the library. Armed with this knowledge, you can now effectively retrieve and manipulate HTML content in your web applications.

FAQ

  1. What is the Fetch API?
    The Fetch API is a modern JavaScript interface for making network requests, allowing you to fetch resources asynchronously.

  2. Can I use XMLHttpRequest in modern applications?
    Yes, XMLHttpRequest is still supported in all major browsers and can be used in modern applications, although the Fetch API is often preferred for its simplicity.

  3. Is jQuery necessary for AJAX requests?
    No, jQuery is not necessary, but it can simplify AJAX requests and provide cross-browser compatibility.

  4. What should I do if the fetch request fails?
    You can handle errors using the .catch() method in the Fetch API or the onerror event in XMLHttpRequest to log or display error messages.

  5. Can I fetch HTML from any URL?
    You can fetch HTML from any URL that allows cross-origin requests. Some URLs may have restrictions due to CORS policies.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe
Harshit Jindal avatar Harshit Jindal avatar

Harshit Jindal has done his Bachelors in Computer Science Engineering(2021) from DTU. He has always been a problem solver and now turned that into his profession. Currently working at M365 Cloud Security team(Torus) on Cloud Security Services and Datacenter Buildout Automation.

LinkedIn