Fetch API in JavaScript and replace HTML element

homepage-banner

To fetch content using JavaScript, you can use the built-in fetch() function or the XMLHttpRequest (XHR) object.

fetch('https://example.com/data.json')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));

In the above code, we first call the fetch() function with the URL of the data we want to retrieve. The fetch() function returns a promise that resolves to the response object.

We then call the json() method on the response object, which returns a promise that resolves to the JSON data. We can then use the retrieved data as needed.

Finally, we use the catch() method to catch any errors that may occur during the fetch operation.

Alternatively, you can use the XHR object to fetch data, as shown below:

const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://example.com/data.json');
xhr.responseType = 'json';
xhr.onload = function() {
  console.log(xhr.response);
};
xhr.send();

In the above code, we first create a new XHR object using the XMLHttpRequest() constructor. We then open a GET request to the URL of the data we want to retrieve.

We set the responseType property to json to indicate that we are expecting a JSON response. We then define an onload event handler that is called when the data is successfully retrieved.

Finally, we send the request using the send() method. Once the data is retrieved, the onload event handler logs the retrieved data to the console.

To put the result of the fetched data into an HTML div, you can modify the code examples I provided earlier. Here’s an example of how you can do it using the fetch() function:

<!DOCTYPE html>
<html>
  <head>
    <title>Fetch Data Example</title>
  </head>
  <body>
    <div id="data"></div>
    <script>
      fetch('https://example.com/data.json')
        .then(response => response.json())
        .then(data => {
          const dataDiv = document.getElementById('data');
          dataDiv.innerText = JSON.stringify(data);
        })
        .catch(error => console.error(error));
    </script>
  </body>
</html>

When the data is successfully retrieved, we use the then() method to convert the response to a JSON object and assign it to the data variable. We then get a reference to the data div using getElementById() and set its innerText property to the JSON string representation of the data.

This will display the fetched data as a string within the HTML div element. You can modify the code to display the data in a different format or structure, depending on your requirements.

Disclaimer
  1. License under CC BY-NC 4.0
  2. Copyright issue feedback me#imzye.com, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected
  5. Partial content rewritten by AI, verified by humans
Feedback