Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to display a blog post using JavaScript without a database is to store the blog post content as a JSON object or an array in a separate file or within the JavaScript code itself.

Here's an example of how to display a blog post using an array:

// Define the blog post array
const blogPost = [
  {
    date: "June 1, 2021",
    title: "My First Blog Post",
    content: "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec aliquam lorem nisi, ac commodo augue vestibulum sit amet. Praesent blandit ipsum a ante tristique."
  },
  {
    date: "June 5, 2021",
    title: "My Second Blog Post",
    content: "Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Duis eu massa lobortis, convallis mauris ut, luctus magna."
  }
];

// Loop through the blog post array and display the content on the page
blogPost.forEach(post => {
  const container = document.createElement("div");
  const date = document.createElement("h2");
  const title = document.createElement("h1");
  const content = document.createElement("p");

  date.innerHTML = post.date;
  title.innerHTML = post.title;
  content.innerHTML = post.content;

  container.append(date, title, content);

  document.querySelector("#blog").appendChild(container);
});

In this example, the blogPost array contains two blog posts with their respective dates, titles, and content. The forEach loop iterates through the array and creates HTML elements for the date, title, and content of each blog post. These elements are then appended to a container div and added to the HTML page using document.querySelector("#blog").appendChild(container);.

This is a simple way to display blog posts without relying on a database. However, it does require manually updating the blog post array whenever new posts are added or edited.