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

Modifying the appearance of the login field shown in the image

How can I align the login and password fields in the same order on my webpage? When I attempt to adjust their positions using CSS margin commands, both fields end up moving. Any suggestions? ...

What is the best way to define multiple variables in ionic 2 using Angular2 and TypeScript?

I'm brand new to working with ionic2/Angular2/Typescript. My project involves creating a wheel with eight slices, but I'm struggling with how to declare multiple variables. In JavaScript, I've declared them like this: function rand(min, max ...

No location matched any routes

I'm currently working on a notes application, and I've encountered an error when trying to edit the notes. The error message says "No routes matched location id ...". Any idea what could be causing this issue? The approach I'm taking is to ...

Implementing bidirectional data binding with Semantic UI's search dropdown feature in Vue.js

I'm currently facing an issue with the Semantic-UI searchable dropdown and Vuejs data binding. It seems like only one changed option is being model-bound, no matter which dropdown option I select. Here's a snippet of my code. I attempted to use ...

Steps to prevent submission of input field until all necessary fields and checkboxes are filled, disabled the submit button

Check out my basic web application on this sandbox link: codesandbox.io/s/eager-kalam-v1lpg I need assistance with how to prevent the submit button from being enabled until all required fields and checkboxes are filled in. I am fairly new to working with ...

Utilizing icons with vuetify's v-select component: a guide

In the code snippet below, I am using a v-select element to display a list of items filled from an array: <v-select v-model="myModel" :items="users" chips :readonly="!item.Active" label="Required users to f ...

Conditionally enable or disable button by comparing textbox values within a gridview using C# programming

Hey there! I'm currently diving into the world of JavaScript and C#. Feel free to correct me if you see any mistakes along the way. Check out my gridview code snippet below: <asp:GridView ID="GridView1" CssClass="table table-hover table-bordered" ...

What could be causing the padding of my anchor element to extend outside the boundaries of its parent list

In the provided images, it is evident that the <li> element is failing to expand and is disregarding the padding of the parent element.</p> <p><a href="https://i.stack.imgur.com/4ZH65.png" rel="nofollow noreferrer"></a></p& ...

Conceal descendant of list item and reveal upon clicking

In my responsive side menu, there is a submenu structured like this: .navbar ul li ul I would like the child menus to be hidden and only shown when the parent menu is clicked. Although I attempted to achieve this with the following code, it was unsucces ...

Developing maintenance logic in Angular to control subsequent API requests

In our Angular 9 application, we have various components, some of which have parent-child relationships while others are independent. We begin by making an initial API call that returns a true or false flag value. Depending on this value, we decide whether ...

ReactJS: Error in syntax detected in src/App.js at line 16, column 6. This token is unexpected

Just starting out with reactjs and encountered a simple example in a tutorial. Ran into a syntax error when trying to return html tags. Below is the error that popped up: ./src/App.js Syntax error: C:/Users/react-tutotial/src/App.js: Unexpected token ...

Adjust the viewing area dimensions on a web browser

Recently, while testing a web application page I developed with Selenium, I came across an interesting issue. After using the JavaScriptExecutor in Selenium to get the viewport size, I found that it was different for Chrome, IE, and Firefox. The sizes wer ...

Prevent FullCalender date cells from resizing when additional events are added

I am currently utilizing JQuery's FullCalendar plugin for my project and I have observed that the date cells expand when multiple events coincide on a single date. For example, as shown in this image, the date cell for February 4 is expanding. Is the ...

Encountering a script error that reads "TypeError: $ is not defined as a function

I am attempting to send an email using web services in asp.net, utilizing html and sending the information through a jquery ajax function. Below is the html form: <div class="col-md-6"> <h2>DROP ME A LINE</h2> & ...

What is the best location for implementing role-based authentication in a MeanJS application?

I am working with a meanJS starter template that includes a yeoman generator. I'm trying to figure out where I can add specific permissions to my modules. For example, 'use strict'; // Configuring the Articles module angular.module(' ...

How do you write functions in ES6?

When attempting to access my namespaced store in Vue, I encountered an issue: methods: { ...mapActions('Modal', [ 'toggleActive', ]), close: () => { this.toggleActive(); } This resulted in the follow ...

Issues with HTML5 video playback have been reported in both Chrome and Firefox browsers

I'm having trouble getting the following HTML5 Video code to work. Can someone help me spot what I might be missing? <video width="267" poster="Poster.gif" height="209"> <source src="6Minutes_1.mp4" type="video/mp4"></source> <so ...

Tips for selecting the initial and final elements of a specific class

Here is a simple example of table markup: <div class="table"> <div class="table__headers"></div> <div class="table__row"></div> <div class="table__row"></div> </div& ...

Error encountered at /edit-menu/edit/: The 'Product' object does not contain the attribute 'is_valid'

I am attempting to extract all product names from the Product model, display them along with their prices on the screen, and enable users to modify the price of any item. Although I have managed to list them out and provide an input field for the price, I ...

Having trouble with @babel/plugin-proposal-optional-chaining in Vue.js <script> tag

While working on my vue/vuetify project and attempting to implement optional chaining, I consistently run into an error: ./src/App.vue?vue&type=script&lang=ts& (./node_modules/cache-loader/dist/cjs.js??ref--0-0!./node_modules/vue-loader/lib??v ...