Being required to design a distinct div for every article I am extracting from the API

In the midst of developing a website for my college project, I have successfully configured my news API to pull and display data using JavaScript.

Currently, I am faced with the challenge of having to create separate div elements each time I want to add new data to one of my article fields. This process is becoming messy as I aim to populate multiple articles with this data without the need to continuously create new divs.

Is there a way to optimize this by having a single article-image div and dynamically generating new ones to populate them with API data based on array values?

var url =
  "HIDDEN_API_KEY";
  
// Fetch request
var req = new Request(url);
fetch(req)
  .then(function(response) {
    return response.json();
  })
  .then(function(res) {
    console.log(res);

// Populating div elements
document.getElementById("stadium_name").innerHTML = (res.articles[1].title);
document.getElementById("stadium_description").innerHTML = (res.articles[1].content);

var articleimg1 = document.getElementById('article-image1');
articleimg1.appendChild(document.createElement('img')).src = (res.articles[1].urlToImage);

...
  });
   <div class="col-md-3 d-flex align-items-stretch">
                <div class="card mt-4 stadiumCard">
                    <h3 id="stadium_name"></h3>
                    <div id="article-image1"></div>
                    <p id="stadium_description">
                        - Text content here -
                    </p>
                </div>
            </div>

            // Additional card structures similar to the first example

Answer №1

To streamline the process, you can develop a "Article" class that is responsible for generating new HTML article elements with nested components (such as title, image, description) and populating their content. Upon receiving data from an API response, iterate through it and add the newly created articles to the designated HTML container. Once the container is filled with articles, showcase all of them simultaneously to your user.

class Article {
  constructor(ArticleData) {
    this.article = document.createElement('article');
    this.title = document.createElement('h3');
    this.img = document.createElement('img');
    this.description = document.createElement('p');
    this.populateContainer();
    this.populateContent(ArticleData);
  }
  populateContainer() {
    this.article.appendChild(this.title);
    this.article.appendChild(this.img);
    this.article.appendChild(this.description);
  }
  populateContent(ArticleData) {
    this.title.innerText = ArticleData.title;
    this.img.src = ArticleData.img;
    this.description.innerText = ArticleData.description;
  }
  getNode() {
    return this.article;
  }
}

fetch('APIendpoint')
  .then(res => res.json())
  .then(articles => {
    const wrapper = document.createElement('div');
    articles.forEach(article => wrapper.appendChild(new Article(article).getNode()));
    document.body.appendChild(wrapper);
  })

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Center the image within the div by setting its position to absolute

<div class='img-box'> <img /> //position absolute <img /> //position absolute <img /> //position absolute <img /> //position absolute I am struggling to center the images within this div because of their absolute p ...

React Images: Carousel display issue with images not centered

Is there a way to center the selected image instead of it appearing on the left-hand side? Here is the current behavior: https://i.stack.imgur.com/SUWOK.jpg I am using the following packages in a sandbox environment with Next.js 11 and TailwindCSS 2.2.4: ...

Is there a way to prevent elements from resizing when zooming in or out?

What is the best way to prevent elements from resizing on a standard website when users zoom in (CTRL +)? ...

JQuery fixed div bounces unpredictably when scrolling

Currently, I have a scenario on my webpage where there is a div called RightSide positioned on the far right side below another div named TopBanner. The TopBanner div remains fixed at the top of the screen even when the user scrolls down, which is exactly ...

What is the correct way to define the onClick event in a React component?

I have been encountering an issue while trying to implement an onClick event in React using tsx. The flexbox and button are being correctly displayed, but I am facing a problem with the onClick event in vscode. I have tried several ideas from the stack com ...

How to handle redirection in React when encountering a 404 error with React

Hey there, I'm encountering an issue related to react router. Let's take a look at my App.js file where all the routes are defined: const App = () => ( <div className="App"> <MediaQuery minWidth={700}> {(matches ...

Tips for transferring data from a parent component to a child component in React?

Recently, I've been restructuring a small application that was initially confined to one file by breaking it into its own separate components. Right now, I have a child component called UsersTable which I am displaying within the parent component User ...

How can we achieve a seamless fade transition effect between images in Ionic 2?

My search for Ionic 2 animations led me to some options, but none of them quite fit what I was looking for. I have a specific animation in mind - a "fade" effect between images. For example, I have a set of 5 images and I want each image to fade into the ...

What is the best way to add a color swatch image using Javascript?

I'm facing a challenge in Shopify where I need to assign corresponding background images to color swatches. Currently, my icons are set up with the correct links for each color, but they are missing their respective images, similar to this example. I ...

What is the best way to get rid of a connect-flash notification?

I'm having trouble removing the message (with the username displayed) after logging out by pressing the logout button. Every time I try to press the logout button, it just refreshes the page without any action. I want to stay on the same page and not ...

Can you explain Node.js and its applications as well as how it is commonly used?

A while back, during my time at IBM when I was immersed in learning, I came across something known as BlueMix, a cloud product. Within BlueMix, there was a rather primitive component called Node.js. Since that moment, I've been filled with curiosity a ...

Retrieve the minimum and maximum values from a multi-dimensional array

If my array consists of the following subarrays: array = [[1, 5, 8, 9], [3, 7], [3, 8, 33], [2], [0, 6]] I am looking to determine the maximum and minimum values in this array. For example, in this case: max = 33, min = 0 While I have come across exampl ...

Enhancing Website Functionality: How to Swap iFrame for DIV using PHP and AJAX

I am currently working on a website where I need to replace an iframe containing data stored in an invisible form with a div that updates its content using AJAX. If you don't want to read everything, skip to the end for my main question. The chall ...

Side navigation in Angular is not causing the main content to shrink

In my layout, I have a container that includes two sidenavs and multiple tables in between them. When I toggle the left sidenav, instead of the expected behavior where the content shrinks to accommodate the sidenav, the tables get pushed to the right as if ...

What causes the discrepancy in pixel size between these two web pages on the same device?

I am currently putting together a portfolio showcasing the projects I have worked on while learning to code. Each project page has a banner at the top, but I'm encountering an issue with one site (Jubilee Austen page) that is unresponsive. After usin ...

Developing a personalized loop in handlebars templates

Just starting out with NodeJS and ExpressJS. I'm looking to customize a for loop in order to iterate through data from NodeJS using an index, akin to a non-traditional for loop. Take a look at the code snippet below, extracted from NodeJS, where I re ...

Populating fields in a new AngularJS document from a table

I have a project where there is a table displaying different instances of our service, and each row has an info button that opens a form with the corresponding row's information autofilled. However, I am facing an issue where by the time I retrieve th ...

Exploring ways to access data stored in interconnected models, such as MongoDB and NodeJS

As a newcomer to querying, I attempted a unique exercise to practice but unfortunately did not achieve the desired outcome. I have three models: const userSchema = new Schema({ info1: String, info2: String }, const serviceSchema = new Schema( { name ...

What is the process for submitting and storing a collection of files in a database as a list?

I am trying to implement a feature in my MVC project where users can upload multiple files and see them listed before submitting the form. However, I am facing some challenges with finding a solution for this. Demo: My goal is to allow users to add multi ...

Removing an element from an array within MongoDB

After closely examining my mongodb data structure, it appears like this: [ { "_id": "582bc918e3ff1bf021ae8b66", "boardName": "Test Board", "created_at": 1479264483957, "__v": 0, "person": [ { "name": "Steve", "w ...