Creating dynamic elements in JavaScript utilizing Bootstrap cards

Looking for help in integrating Bootstrap cards while dynamically generating elements using JavaScript?

I am working on a project where I need to generate a list of restaurant recommendations based on user preferences entered through a form, utilizing the Yelp Business Search and Google Maps APIs. I want each recommendation to be displayed within a Bootstrap card for better organization and visual appeal. However, I'm struggling to find resources or examples that demonstrate how to achieve this with JavaScript.

The current code I have generates the list of recommendations using the data retrieved from my API calls. I aim to present each restaurant along with its information in a Bootstrap card layout for a cleaner look on my webpage. As a novice software engineering bootcamp student, any advice or guidance on how to accomplish this task would be greatly appreciated.

function updateResults(data, userLocation) {
  const resultsContainer = document.getElementById("results-container");
  const mapContainer = document.getElementById("map-container");

  // Clear any existing results from the container
  resultsContainer.innerHTML = "";
  
  // Initialize the map with user's location and search results
  initMap(userLocation, mapContainer, data.businesses);

  // Loop through the search results and create HTML elements for each one
  data.businesses.forEach(result => {
    const resultElement = document.createElement("div");

    const nameElement = document.createElement("h2");
    const nameLink = document.createElement("a");
    nameLink.href = result.url;
    nameLink.innerText = result.name;
    nameElement.appendChild(nameLink);

    const imageElement = document.createElement("img");
    imageElement.src = result.image_url;
    imageElement.style.width = "100px";
    imageElement.style.height = "100px";
    imageElement.style.objectFit = "cover";

    const addressElement = document.createElement("p");
    addressElement.innerText = result.location.display_address.join(", ");

    const distanceElement = document.createElement("p");
    if (result.distance_data.distance){
      distanceElement.innerText = `${result.distance_data.distance.text} miles from your location`;
    }
    
    const durationElement = document.createElement("p");
    if (result.distance_data.duration){
    durationElement.innerText = `${result.distance_data.duration.text} minutes from your location`;
    }

    const priceElement = document.createElement("p");
    priceElement.innerText = result.price;

    const ratingElement = document.createElement("p");
    ratingElement.innerText = `${result.rating} stars`;

    // Append all elements to the result element
    resultElement.appendChild(nameElement);
    resultElement.appendChild(imageElement);
    resultElement.appendChild(addressElement);
    resultElement.appendChild(distanceElement);
    resultElement.appendChild(durationElement);
    resultElement.appendChild(priceElement);
    resultElement.appendChild(ratingElement);

Answer №1

Make sure to assign the necessary classes to each element before inserting them into the document.

resultElement.className = 'card';
// You may also want to define resultElement.style.width
imageElement.className = 'card-img-top';
resultElement.append(imageElement);
const body = document.createElement('div');
body.className = 'card-body';
nameElement.className = 'card-title';
body.append(nameElement, addressElement, distanceElement, durationElement, priceElement, ratingElement);
resultElement.append(body);
resultsContainer.append(resultElement);

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

Angular: What methods can I utilize to prevent my $http requests from causing UI blockage?

The following code snippet is from my controller: PartnersService.GetNonPartnerBanks().success(function (data) { vm.nonPartnerBanksList = data; }).error( function () { vm.nonPartnerBanksList = []; }); This code calls the service s ...

Unable to add new tags in Vue multiselect component

Currently, I am utilizing a Vue Multiselect instance with two functions. One function interacts with the database to provide autocomplete functionality, which is working successfully. The second function allows for adding new tags that are not present in t ...

What is the best way to use res.sendFile() to serve a file from a separate directory in an Express.js web application?

I have a situation within the controllers folder: //controler.js exports.serve_sitemap = (req, res) => { res.sendFile("../../sitemap.xml"); // or // res.send(__dirname + "./sitemap.xml") // But both options are not working }; ...

Is it possible to eliminate the array from a property using TypeScript?

Presenting my current model: export interface SizeAndColors { size: string; color: string; }[]; In addition to the above, I also have another model where I require the SizeAndColors interface but without an array. export interface Cart { options: ...

Vue 3's defineExpose feature does not allow for the exposure of child methods or properties

I have a main component and subcomponent set up as shown below: Main Component : <script setup> import SubComp from '@/components/SubComp.vue' import { ref, computed } from 'vue' const subComp = ref(null) const handleClick = () ...

After placing two divs within another div and applying justify content, an unexpected blank space has appeared

I am currently working on a website project using the Next.js framework for React and Tailwind CSS for styling. However, I have come across an issue that is causing some trouble. My goal is to position an image on the right side of the page while keeping t ...

Exploring the power of Vue.js by utilizing nested components within single file components

I have been attempting to implement nested single file components, but it's not working as expected. Below is a snippet of my main.js file : import Vue from 'vue' import BootstrapVue from "bootstrap-vue" import App from './App.vue&apos ...

Finding Text Between Two Distinct Strings Using Regular Expressions in JavaScript

I am currently utilizing AJAX technology. My approach involves sending a GET request that retrieves a raw HTML string representing the content of a webpage. I am grappling with the challenge of isolating all elements enclosed between div tags: <div ro ...

What are the best practices for presenting Motion JPEG binary data streams using Angular, Ionic, and JavaScript?

I am developing an application for a device that will receive a POST request and send back a binary data stream in the format of multipart/x-mixed-replace. My goal is to display this stream on a specific section of my app's homepage. After conducting ...

What could be causing my React app to consistently reload whenever I save a file in my project?

Hi there, I am currently working on a project using React, GraphQL, Node, and MongoDB. I have been trying to upload images to a folder within my app, but I am facing an issue with the app reloading after saving the file. I attempted to manage a local state ...

Prevent the Icon in Material UI from simultaneously changing

I'm working on a table where clicking one icon changes all icons in the list to a different icon. However, I want to prevent them from changing simultaneously. Any suggestions on how to tackle this issue? Code: import React from 'react'; im ...

Associating the object key and value with distinct attributes within the component

person = {name: 'Alice', age: '19', weight: 52} I'm looking to display both the keys and values from the object in one label and input field respectively. I attempted using Object.entries, but couldn't figure out how to sepa ...

What could be causing my Jquery fade effect to not function properly?

I'm new to incorporating Jquery into my website and I'm facing an issue with getting the first row of pictures to fade in (upwards) when scrolling. Despite my efforts, they are not behaving as expected. Any guidance on how to resolve this? HTML: ...

How to extract a particular value from a JSON object using AJAX?

In my test.php file, I have implemented a code where ajax sends a request from index.php to this page. Within this page, I have created an array, converted it to JSON, and returned it as follows: <?php $arr = array( "status"=>200, "result"=>array ...

Linked selection options for state, city, and postal code

I have set up a cascading dropdown list - State -> City -> Pincode . Instead of fetching data from the database, I am using JSON. The dropdown functions smoothly on the local server, but experiences slowness on the web server. Here is a snippet of ...

"Mastering the art of displaying real-time data on a thermometer using D3.js

Welcome to the sample code for a thermometer created using D3.js. You can view the code on jsfiddle. I've developed a web page displaying a dynamic thermometer with values updating every second. Here's the function: setInterval(function(){ getN ...

Spreading an object to remove a key may result in the returned value being

When creating a Radio Button object, each object in the array consists of {value: 1, text: 'Sometext'}. If a radio button is selected, 'selected: true' is added to that specific object and removed from the others. const onChoiceChange ...

Using jQuery, effortlessly scroll a div to a specific vertical position of your choice

After referring to this previous question: Scrollpane on the bottom, css is hacky, javascript is hard I followed the same scrolling method as explained in the accepted answer. Now there's a new requirement to select a specific item (e.g., through a ...

There was an error during module build process: ReferenceError occurred due to an unrecognized plugin "import" specified in "base" at position 0

I have encountered an error while working on my ReactJS project using create-react-app. The error arose after I added and removed a package called "react-rte". Now, every time I try to start my project, I get the following error: Error in ./src/index.js Mo ...

Accessing specific values from a JSON object in JavaScript

I'm fairly new to JSON and have a JSON String that I'd like to access and print to a DIV. I've managed to get it working using the following code snippet: document.getElementById("product_content").innerHTML=javascript_array[5].name; The s ...