What is the best way to showcase the contents of an array of objects from JavaScript on an HTML page in a dynamic

Looking for guidance in Javascript as a beginner. For an assignment, I need to create two separate JS files and use them to display data dynamically on an HTML page. One JS file, named data.js, contains an array of objects representing a product catalog. The other JS file includes a function that is supposed to load these items, generate HTML elements, and display the products on the webpage. However, my code isn't functioning correctly and the products are not being displayed in the desired format. Additionally, it seems like the CSS styles are not being applied within the function as well. To address certain syntax issues, I have commented out some sections of code in the `loadProducts()` function.

// data.js
var catalog = [
    {
      code: 100,
      name: "Learn JS",
      desc: "To make your web pages dynamic",
      price: 150,
      image: "/images/100Tshirt.jpg"
    },
    {
      code:101 ,
      name: "T Shirt",
      desc: "Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.",
      price: 0,
      image: "/images/101Tshirt.jpg"
    },
  
     {
      code:102 ,
      name: "T Shirt",
      desc: "Lorem ipsum, or lipsum as it is sometimes known, is dummy text used in laying out print, graphic or web designs.",
      price: 0,
      image: "/images/102Tshirt.jpg"
    }
  
    // {
    //   name: "Meowsalot",
    //   species: "Cat",
    //   favFoods: ["tuna", "catnip", "celery"],
    //   birthYear: 2012,
    //   photo: "https://learnwebcode.github.io/json-example/images/cat-1.jpg"
    // 
  ];
  
 // codeboutique.js
 function chargerArticles() {
var articles = document.getElementById("content");
 
 for (var i =0; i <= catalog.length; i++) {

var article = document.createElement("div"); 
article.setAttribute("class", "addClass");

var articleName = document.createElement("h2");
articleName.setAttribute("class", "heading"); 
articleName.innerText = catalog[i].name;
article.appendChild(articleName);
    articles.appendChild(article);

  var articleImg = document.createElement("img");
articleImg.setAttribute("class", "imgclass class2 class3");
articleImg.setAttribute("src", catalog[i].image);
article.appendChild(articleImg);
}
}
.addClass
{
font-size: 44px;
color:grey;
background-color: blue;
border-style: 2px solid yellow;

}
.heading
{
color: green;
}

.border {
  border: 1px solid grey;
}

.pad {
  padding: 15px;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8>
    <title>Page Title</title>
    <script src="js/data.js"></script>
    <script src="js/codeboutique.js"></script>
    <link rel="stylesheet" type="text/css" href="css/mystyle.css">

</head>

<body onload="chargerArticles()">
    <section id="content">
    </section>

</body>

</html>

Any assistance would be greatly appreciated. https://i.sstatic.net/NwDYx.png

Answer №1

Take a moment to review the guidelines displayed in your screenshot. I noticed that there are some important instructions there that you seem to have overlooked, which could possibly resolve your issue.

In particular:

Make sure to insert articleName as a child element of the article element

appendChild() (mentioned in your comment) is indeed the correct function to use, but it seems like you're calling it from the wrong object (document.body). Reevaluate your approach to this problem.

I suspect that further down the line, there might be an instruction to add the article as a child of the catalog table ("articles").

You might find it a bit confusing that you're not using the suggested variable names provided in the assignment instructions. While it's possible to make the code work with different variable names if you know what you're doing, since you mentioned being a beginner, I would recommend sticking closely to the given guidance for now.

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

Deciphering unidentified Json data

Having some trouble with an error in my note taker app built using expressjs. Everything was working fine until I tried to save a new note and it's throwing this error: SyntaxError: Unexpected token o in JSON at position 1 at JSON.parse () Here&apos ...

Send the ID of the checkbox to a PHP file using AJAX

Is it possible to generate a network graph by selecting checkboxes? When I choose one or more checkboxes and click the button, I expect to see a network graph with the selected checkboxes. It almost works, but when I select multiple checkboxes, only one ...

Transition effortlessly between web pages with subtle fading effects

I want to implement smooth page transition effects between two web domains: mcpixel.co.uk/new and mcpaper.co.uk. I am the owner of both domains. When a link in the header is clicked, I'd like the page to fade transition to the new page without any whi ...

Retrieve a specific element using BeautifulSoup

Looking at this html structure found in a bs4.BeautifulSoup: <div class="bordered radius border-color-ui-2 bg-white h-100"> <a href="#" class="box-card-link-wishlist" role="button" aria-label="Adicion ...

jQuery Form Validator: requiring double submission

I've been working on implementing the Form Validator using Jquery. After some testing, I noticed that I have to click the submit button twice before the validation kicks in. Why is that? The script is housed in a separate file and included in my proj ...

Do you think it's achievable to modify the color using CSS's order attribute?

When I look at the code in Firefox's inspector, I notice this : element { order:35; } Can a color be assigned to it? I am customizing my year outlook calendar and have set a particular day to display in a different color. But when I click on the mo ...

Cease the progress of a Sequelize promise within an Express.js application

Exploring the realm of promises is a new adventure for me, and I'm still trying to grasp their full potential in certain situations. It's refreshing to see Sequelize now supporting promises, as it greatly enhances the readability of my code. One ...

A combination of fixed width column and dynamic content area in Bootstrap design

Is there a way to achieve the combination of fixed and fluid width columns using Twitter Bootstrap alone, similar to this example? The HTML and CSS in the example make it seem simple. But can this be done solely with Bootstrap? ...

Struggling with calling rerenderEvents in FullCalendar using JQuery after a successful AJAX request

I seem to be encountering an issue where the calendar does not update after a POST request. Everything works smoothly until that point: $('#calendar').fullCalendar({ ... select: function (startDate, endDate) { $.ajax({ ...

Getting the dimensions of an image when clicking on a link

Trying to retrieve width and height of an image from this link. <a id="CloudThumb_id_1" class="cloud-zoom-gallery" rel="useZoom: 'zoom1', smallImage: 'http://www.example.com/598441_l2.jpg'" onclick="return theFunction();" href="http ...

Ensuring consistency of Angular route data and maintaining data synchronization

In my Angular application, I have a table that displays a set of items and allows inline editing directly within the table. The data is fetched from an HTTP API through a service, which retrieves the data and injects it into the application. The issue ari ...

What is the best way to consistently position a particular row at the bottom of the table in AG-grid?

I have successfully implemented a table using AG-grid. Here is the code snippet: .HTML <ag-grid-angular #agGrid style="width: 100%; height: 100%; font-size: 12px;" class="ag-theme-alpine" [rowData]=&quo ...

What is the best way to distinguish between enabled buttons using Protractor?

I am facing a challenge with a table containing 20 buttons. Half of these buttons are disabled while the other half is enabled. I am looking for a way to filter out the enabled buttons and click on each of them using a for loop. The buttons that I want to ...

Obtain a collection of information from a web API by utilizing jQuery

Click on the following link to access live data from a web API: This is my first attempt at retrieving data from an API, so I may have missed some settings. To test the connection with the API, I included the following code in the HTML page: <div id= ...

Keeping Materialize CSS color changes distinct from the NPM module: best practices

In my electron application, I am utilizing the npm module materialize-css (version 0.100-2). Since npm modules are not git-tracked, I have made changes to the SASS components within the following files: node_modules/ +-- materialize-css/ +-- sass/ ...

Exploring the depths of recursion with jQuery: Unraveling the

Having some issues with a recursive function in jQuery that's throwing an exception: 'Uncaught RangeError: Maximum call stack size exceeded' I can't figure out why this recursive function might be running infinitely. Any help would be ...

Elements floating and creating gaps (caused by varying heights)

I am working on developing a responsive webpage. This is what I am aiming to achieve. View jsfiddle #container { max-width:500px; width:100%; color: #fff; } #one { width:300px; height:200px; background:#66BCD9; float:left; } #two { wid ...

Using Ruby instead of Javascript in lessc

My CSS is compiled in a node application using lessc. LESS was installed via NPM. When I check the current version of lessc --version it shows lessc 1.3.3 (LESS Compiler) [Ruby] 2.3.2 How can I change it to display lessc 1.3.0 (LESS Compiler) ...

Creating an infinite SVG animation loop using JavaScript

elem = document.querySelectorAll("path"); function task(i) { setTimeout(function() { elem[i].animate({fill: 'green'}, { // timing options duration: 150, iterations: 1 }); }, 150*i); } for(var i=0;i<8;i++){ task(i); } < ...

What's the best way to ensure that a div remains fixed at the top of the page while also being centered?

I have a div that I've centered using margin left and right auto. However, I want this bar to be visible throughout my page, so I positioned it absolutely. But now the bar is not centered anymore, it's appearing on the left. How can I position th ...