Ask Your Question
0

How can a blog post be displayed using JavaScript without using a database?

asked 2023-06-05 18:18:07 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2023-06-05 18:35:01 +0000

djk gravatar image

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.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-06-05 18:18:07 +0000

Seen: 19 times

Last updated: Jun 05 '23