Step-by-step Guide on Utilizing Bootstrap Table

Currently, I am in the process of fetching data from an API and displaying it in a tabular format using JavaScript. While I have successfully retrieved the data, I'm facing an issue with applying Bootstrap styling to the table headers.

async function Sports() {
  let Api = "https://inshortsapi.vercel.app/news?category=sports";
  let result = await (await fetch(Api)).json();

  document.write(`   <table class='table'>
                                <thead class='thead-dark'>
                                 <tr><th>SR NO</th>
                                     <th> AUTHOR NAME</th>
                                     <th>CONTENT</th>
                                     <th>DATE </th>
                                 </tr></thead>`);

  for (var i = 0; i < result.data.length; i++) {

    document.write(`<tbody><tr>
                                        <td>${i+1}</td>
                                        <td>${result.data[i]["author"]}</td>
                                        <td>${result.data[i]["content"]}</td>
                                        <td>${result.data[i]["date"]}</td>
                                    </tr></tbody>`)
  }
  document.write("</table>")
}
Sports();
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="27454848535453554657671209140914">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ea9a859a9a8f98c48099aadbc4dbdec4d9">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="14767b7b60676066756454203a253a27">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

I am envisioning a table design like this []

Regrettably, the outcome I ended up with was not as expected, and the table format looked different from what I had in mind.

https://i.sstatic.net/XrMnV9cg.png

Answer №1

Using document.write will overwrite your existing HTML, including any Bootstrap imports you may have.

To add elements without overriding your existing content, you can use

document.body.insertAdjacentHTML('afterbegin', "<table>...</table>")
.

async function Sports() {
  let Api = "https://inshortsapi.vercel.app/news?category=sports";
  let result = await (await fetch(Api)).json();

  let html = `   <table class='table'>
                                <thead class='table-dark'>
                                 <tr><th>SR NO</th>
                                     <th> AUTHOR NAME</th>
                                     <th>CONTENT</th>
                                     <th>DATE </th>
                                 </tr></thead>`

  for (var i = 0; i < result.data.length; i++) {

    html += `<tbody><tr>
                                        <td>${i+1}</td>
                                        <td>${result.data[i]["author"]}</td>
                                        <td>${result.data[i]["content"]}</td>
                                        <td>${result.data[i]["date"]}</td>
                                    </tr></tbody>`
  }
  html += ("</table>")
  document.body.insertAdjacentHTML('afterbegin', html)
}
Sports();
<link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385a57574c4b4c4a5948780d160b160b">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="19697669697c6b37736a592837282d372a">[email protected]</a>/dist/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d5d8d8c3c4c3c5d6c7f78399869984">[email protected]</a>/dist/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>

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

Issues arise when implementing a sticky position using CSS with incomplete functionality

I want to create a website with a menu bar that stays at the top even on long pages. However, when I use position: sticky in CSS, the menu disappears after scrolling a certain distance. Does anyone know how to fix this issue? HTML: <nav> <ul cla ...

How to automatically refresh a page in Vue.js when a button is clicked

I am trying to achieve a page refresh when I click the button. Below is the HTML code for the button: <button v-on:click="getUser()" :class='gender'>Get Random User</button> Here is the JavaScript code: const app = Vue.crea ...

Quick method for handling arrays to generate waveforms

I'm currently working on optimizing the code for my web application. While it functions, the performance is a bit slow and I am looking to make improvements: The main concepts behind the code are: The function retrieves the current buffer and conve ...

The checkbox is failing to display as checked even after its value has been dynamically set to true

Currently, I am immersed in a project within ASP.NET MVC that involves displaying data on a page where users can interact by selecting checkboxes to make changes. In cases where there are numerous checkboxes present, a "Select all Checkboxes" button become ...

Comparing XDomainRequest and XMLHttpRequest for IE8 and IE9: A detailed analysis

I am feeling pretty lost when it comes to understanding the XMLHttpRequest and XDomainRequest renaissance, and I could really use some guidance. Here are my thoughts so far: It seems like the XDomainRequest in IE8 and IE9 is some sort of subclass of XMLH ...

Displaying errors above the table. Executing ng-repeat in AngularJS

I've been struggling with a seemingly simple issue for hours now. I have a table displaying equipment rows using ng-repeat and input controls, and I want to display validation errors above the table. Here's what I tried: <div class="col-xs- ...

Managing JSON data sent using PHP

After exploring numerous syntaxes from various sources on the internet, I am hesitant to reveal my struggles as it may be hard to distinguish fact from fiction. So... This snippet shows a part of my HTML code: var jsonData = { address: 'address& ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

Retrieve both positive and negative reviews using the Steam API

I'm trying to calculate the percentage of positive reviews, but I haven't been able to find the necessary data. I've been using this endpoint to retrieve game information: "", but it only provides the total number of reviews. I am aware of a ...

Floating action buttons in CSS

I'm trying to create a button that reveals additional options when hovered over. I've been looking for a method similar to what's shown in the image below, but haven't been successful. This needs to be implemented on a web page using HT ...

Is it possible to utilize "this" in mapMutations spread within Vue instance methods?

Trying to define Vuex mutations like this: export default { props: { store: String }, methods: { ...mapMutations({ changeModel: `${this.store}/changeModel` }) } } Encountering an error message: An er ...

The leaflet.js library threw an error: LatLng object is not valid due to invalid coordinates (NaN, NaN)

Currently, I am working with a JSON file that contains coordinates in pairs. "_id" : ObjectId("59407457838b932e0677999e"), "type" : "MultiPoint", "name" : "points", "coordinates" : [ [ -73.958, 40.8003 ], ...

Generating a JSON file using JavaScript amidst the presence of unconventional characters in JSON keys

In my Node Red Function Node, I'm currently facing a challenge of generating a JSON file from JavaScript code. The specific format I need for the JSON file is as follows: [ { "H-Nr.":"1", "Pos.-Nr.":"1" }, { "H-Nr.":"1", ...

Is it possible to dynamically add elements in AngularJS without relying on directives?

As a newcomer to Angularjs and not very fluent in English, I embarked on the journey of adding <li> using directives. You can see the result of my first attempt at this link. Next on my list was mastering two-way binding by passing values between th ...

Revealing Transition Element on mouseover

My side-menu consists of icons that display text to the right upon hovering over them. I want the text to show up and the div to expand smoothly with a sliding transition, ideally without the need for additional JavaScript. Is there a way to achieve this? ...

Validation in ASP.Net to ensure the correct number of days between the arrival and departure dates

One of my project requirements involves checking the validation of the number of days entered between two date selectors (From & To Dates). The constraint is that the difference should not exceed 100 days. I'm considering using ASP.NET validators for ...

Execute JavaScript function on click event in NextJS

Is it possible to execute a JavaScript function on the client side without using addEventListener? This situation works with addEventListener. MyComponent.js import Script from 'next/script' export default function MyComponent({ props }) { ...

Move the Bootstrap button to the right side of the div, extending beyond its boundaries

My bootstrap page seems to be experiencing an issue where the buttons within a div are shifted slightly to the right without any clear reason: https://i.sstatic.net/3xlMC.png https://i.sstatic.net/yFLFM.png https://i.sstatic.net/gh686.png The div in qu ...

Getting the IDs of selected nodes all the way up to the root node in jsTree

How can I retrieve the IDs of all parent nodes from a selected node to the root node in jsTree? If node C is selected, how can I obtain the IDs of all its parent nodes? Tree Structure: B C +C1 +c2 The following code snippet only returns the imme ...

Automatic Update Division in Jade Template (Node.js/Express)

In my development project using Node.js, Express, Jade, and Redis, I have successfully created an app that pulls telnet stream data from reversebeacon.net. This data is then cross-referenced with Redis databases containing amateur radio club member informa ...