Displaying array elements on a webpage using JavaScript in HTML

Looking to display multiple blocks in HTML using a JavaScript array. The array contains names such as:

var name=['amit','mayank','jatin'];
. I need to repeat a certain portion of code in order to show the elements of the array, with 10 names fetched from the backend.

<div class="limiter">
        <div class="container-table100">
            <div class="wrap-table100">
                    <div class="table">

                        <div class="row header">
                            <div class="cell">
                                Rank
                            </div>
                            <div class="cell">
                                Name
                            </div>
                            <div class="cell">
                                Quiz Name
                            </div>
                            <div class="cell">
                                Scores
                            </div>
                        </div>
//repeat below code for each name in the array
                        <div class="row">
                            <div class="cell" data-title="Full Name">
                                1
                            </div>
                            <div class="cell" data-title="Age">
                                Amit Singh
                            </div>
                            <div class="cell" data-title="Job Title">
                                Python Quiz
                            </div>
                            <div class="cell" data-title="Location">
                                100
                            </div>
                        </div>
//till here
                    </div>
            </div>
        </div>
    </div>

Answer №1

There are various ways to achieve this task, and here is one of them.

In the scenario outlined above, we utilize a querySelector to select the element with the class name data, allowing us to insert HTML code in that specific location.

The map() method comes into play by executing the provided function for each element within an array sequentially. This enables the creation of a table containing all the data from the array.

I trust that this explanation proves helpful to you.

const dataElement = document.querySelector('.data');

const data = [
  {fullName: 'Nathan', age: 21, jobTitle: 'Programmer', location: 'IRAN'},
  {fullName: 'Ali', age: 21, jobTitle: 'Programmer', location: 'UK'},
  {fullName: 'Ariana', age: 21, jobTitle: 'Programmer', location: 'US'},
];

data.map(item => {
  dataElement.insertAdjacentHTML('afterbegin', `
      <div class="cell" data-title="Full Name">
          ${item.fullName}
      </div>
      <div class="cell" data-title="Age">
          ${item.age}
      </div>
      <div class="cell" data-title="Job Title">
          ${item.jobTitle}
      </div>
      <div class="cell" data-title="Location">
          ${item.location}
      </div>
`)
})
<div class="limiter">
        <div class="container-table100">
            <div class="wrap-table100">
                    <div class="table">

                        <div class="row header">
                            <div class="cell">
                                Rank
                            </div>
                            <div class="cell">
                                Name
                            </div>
                            <div class="cell">
                                Quiz Name
                            </div>
                            <div class="cell">
                                Scores
                            </div>
                        </div>
//repeat below code
                        <div class="row data">
                        </div>
//till here
                    </div>
            </div>
        </div>
    </div>

Answer №2

Stringify the specified element, iterate through the provided array, then utilize insertAdjacentHTML for insertion.

const names = ['sam', 'maya', 'jake'];

const tableBody = names
  .map((name) => `
    <div class="row">
      <div class="cell" data-title="First Name"&vitaminacid.com.au..squalaneFaceOil #-bitlizard-websiteionDesignUI>1</div>
      <div class="cell\" data-title=\"Age\">${name}<-iiden suit;br /> -Androzicna lekovaTo-</div>
      <div class="cell" data-title="Job Title">Java Development</div>
      <div class="cell" data-title="Location">150<p></div>`).join('');

const rowHeader = document.querySelector('.table > .header');

rowHeader.insertAdjacentHTML('afterend', tableBody);

Answer №3

To display a table on your webpage, you can create an array of objects containing information such as name, age, job, and location. Then, iterate through this array to generate HTML strings for each entry which will be appended to the table element in your HTML.

const tableEl = document.querySelector('.table');
let htmlToAppend = "";
let data = [
    {
        name: 'Sarah Smith',
        age: 25,
        job: 'Engineer',
        location: 'San Francisco'
    },
    {
        name: 'Alex Brown',
        age: 35,
        job: 'Designer',
        location: 'Los Angeles'
    },
    {
        name: 'Emily Green',
        age: 40,
        job: 'Artist',
        location: 'Paris'
    },
    {
        name: 'Tom Davis',
        age: 22,
        job: 'Developer',
        location: 'Berlin'
    },
    ];

data.forEach(entry => {
       htmlToAppend += `<div class="row">
                            <div class="cell" data-title="Full Name">
                                ${entry.name}
                            </div>
                            <div class="cell" data-title="Age">
                                ${entry.age}
                            </div>
                            <div class="cell" data-title="Job Title">
                                ${entry.job}
                            </div>
                            <div class="cell" data-title="Location">
                                ${entry.location}
                            </div>
                        </div>`
})

tableEl.innerHTML = htmlToAppend;

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

Struggling with my Transform Origin in CSS for SVG

I have two classes (firstCircle & spin) on the first circle on the left, and I'm attempting to make it rotate in place. After removing them from the css so you can see the circle, I am having trouble with transform-origin. My code seems wrong as i ...

Creating MySQL inserts from various dynamic HTML tables generated using PHP

Currently, I am faced with a challenge while working on a PHP file that produces multiple dynamic HTML tables through the use of an included PHP library. To provide a glimpse, here is a snippet of the HTML output (with just two tables and reduced rows) ava ...

Creating a customized design for your jQuery UI modal dialog box using CSS

I recently had to customize the jqueryui modal dialog in order to meet the standards set by my company. Currently, I am facing a cross-browser issue with the float and width of the input labels. You can view the sample website here: http://inetwebdesign. ...

What is the correct way to convert a JArray into a list of strings?

I have a JArray saved in a variable of type object public object Errors { get; } This variable can store either of the following: Errors = {[ { "name": [ "Username &quot;admin&quot; has already been taken." ], ...

Issue encountered: Cannot locate module: Error message - Unable to find 'stream' in 'C:devjszip-test ode_modulesjsziplib' folder

I am encountering an issue in my angular 7 application while using jszip v3.2.1. During the project build process (e.g., running npm start), I receive the following error message: ERROR in ./node_modules/jszip/lib/readable-stream-browser.js Module not fo ...

Ways to replace CSS classes created using makeStyles

To clarify, my development environment is using MUI version 4.12.3. Inside file A, I have a simplified code snippet for a functional component, along with the usage of makeStyles to style a JSX element within the return statement (not displayed here). Ever ...

I'm curious about the process behind this. Can I copy a Figma component from a website and transfer it into my

Check out this site for an example: Interested in how uikit.co/explore functions? By hovering over any file, a copy button will appear allowing you to easily paste it into your Figma artboard. Want to know how this works and how to implement it on your o ...

Development with Node JS, express, Mongoose, and intricate nested queries

I'm struggling with a group of interconnected queries using express/mongoose, structured like this: app.get(..., function(...) { Schema1.query(..., function(..., res1) { for ( var key in res1 ) { Schema2.query(..., function(..., ...

Working with SASS imports in an isomorphic React app: best practices

Currently, my React app is set up with SSR support as follows: React app Express server that compiles the React app using webpack Using babel-node to run the Express app with ES6 features Everything works fine until I added CSS modules to the React app, ...

Accessing a service instance within the $rootScope.$on function in Angular

I'm looking for a way to access the service instance variable inside the $rootScope in the following code. myapp.service('myservice',function($rootScope) { this.var = false; $rootScope.$on('channel',function(e,msg) { v ...

How can I personalize the HTML code of images added to my WordPress articles?

I've been on an extensive search trying to find a solution for this issue. I'm aiming to modify the markup of an uploaded image in WordPress from its current form: <div id="attachment_906" style="width: 590px" class="wp-caption aligncenter"&g ...

Exploring Angular: Looping through an Array of Objects

How can I extract and display values from a JSON object in a loop without using the keyValue pipe? Specifically, I am trying to access the "student2" data and display the name associated with it. Any suggestions on how to achieve this? Thank you for any h ...

Locate a specific word within a sentence using PHP

Here is a snippet of code I am struggling with: $newalt = "My name is Marie"; I need to check if the words 'marie' or 'josh' appear in the above sentence: $words = array("marie", "josh"); $url_string = explode(" ", $newalt); if (!i ...

CSS rules for organizing the stacking order of elements in the SuperFish Menu with

I've been struggling with a z-index issue on a website I'm currently managing. It seems to stem from the z-index values in the SuperFish Menu and a specific div element. Despite my attempts to apply position:relative/absolute & z-index: 99999 dec ...

What is the best way to apply a CSS class to a div element without affecting its child elements using JavaScript?

Currently, I am using JavaScript to add and remove a CSS class through a click event. Within my div structure, I have multiple similar divs. While I can successfully add and remove the class from my main div, I am facing an issue where the class is also ap ...

Utilizing Express JS to keep users on the same page upon submitting a form

Although this may seem like a simple query with available tutorials, I am struggling to locate the specific information. I utilized express-generator to create an app and included a basic form in a route. views/form.ejs <div> <h1>This is < ...

Java Library for Converting HTML to Textile Format

I have a requirement to convert a String from HTML format to Textile format. After researching various libraries such as Textile4J, Textile-J, JTextile, and PLextile, I found that none of them offer the specific functionality I need. Although they do prov ...

Adjust the size of the plane in Three.js to match the entire view

English is not my strong suit, as I am Japanese. I apologize for any confusion. Currently, my focus is on studying Three.js. I aim to position a Plane directly in front of the camera as the background. My goal is to have the Plane background fill the en ...

The state variable is not accurately captured as it passes through various components

For the sake of readability, I have omitted certain sections of my original code. Apologies if this leads to any confusion! In App.js, there is a state variable defined as follows: const [tasks, setTasks] = useState([]) From App.js, the state varia ...

Solving Cross-Origin Resource Sharing problem in an Express JS application

I have encountered a CORS error while using this code, despite having applied the necessary cross-origin headers. I am seeking guidance on how to resolve this issue. var express = require('express'); var bodyParser = require('body-parser&ap ...