To fetch and display data from an API and update the DOM using JavaScript, you can follow these steps:
Create an HTML file with the necessary structure, including elements where you want to display the fetched data.
In your JavaScript code, use the fetch()
function to send a request to the API and receive the response. For example:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
// Handle the fetched data here
})
.catch(error => {
// Handle any errors that occur during the fetch request
});
then
method of the fetch()
function, process the fetched data as needed. You can access the data in the provided callback function, where you can manipulate it or update the DOM. For example, you can create HTML elements dynamically based on the fetched data and append them to an existing element. Here's an example:fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => {
const container = document.getElementById('container');
data.forEach(item => {
const element = document.createElement('p');
element.textContent = item.title;
container.appendChild(element);
});
})
.catch(error => {
// Handle any errors that occur during the fetch request
});
In the above example, the fetch()
function receives a response from the API, which is then parsed into JSON format using the json()
method. You can then access the response data and manipulate it as needed. In this case, a container element with the id container
is accessed using getElementById()
, and paragraphs (<p>
) are dynamically created and appended to the container element.
Handle any errors that might occur during the fetch request inside the catch
method. You can display an error message or take any other appropriate action as needed.
Make sure to replace https://api.example.com/data
with the actual URL of the API you want to fetch data from and adapt the code to your specific needs.