Use 'fetch' function to access remote data using an API(https://jsonplaceholder.typicode.com/posts) and display it.
Mon Apr 07 2025 23:59:29 GMT+0000 (Coordinated Universal Time)
Saved by
@p9876543
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<h1>Posts</h1>
<div id="posts"></div>
<script>
fetch('https://jsonplaceholder.typicode.com/posts')
.then(response => response.json())
.then(data => {
const postsDiv = document.getElementById('posts');
data.slice(0, 5).forEach(post => {
const postElement = document.createElement('div');
postElement.innerHTML = `<h3>${post.title}</h3><p>${post.body}</p>`;
postsDiv.appendChild(postElement);
});
})
.catch(error => console.error('Error fetching data:', error));
</script>
</body>
</html>
content_copyCOPY
Comments