Adding content to an Array using forEach and updating innerHTML - A step-by-step guide

I'm curious about adding data content inside an array to innerHTML using the forEach method.

For some reason, I can't get it to show up. Is it even possible? I'm dealing with dynamic data, so I need to loop through it and display it using innerHTML.

const showPosts = (data, value) => {
    const btnDiscover = document.querySelector('[data-show="discover"]');

    const slides = data.add_post_slides;

    const Posts = () => {
        return slides.length > 0 && 
            slides
                .map((el) => {
                    return <h2>123</h2>;
                })
                .join('');
    };

    // console.log(Posts());

    btnDiscover.addEventListener('click', (e) => {
        e.preventDefault();
        body.classList.add('toggle-legend', 'no-scroll');

        console.log('Discover clicked');
        console.log(slides);

        theContent = `
        <div class="modal">
            <div class="modal__body">
                <a href="#" id="close"><span class="modal__close"></span></a>

                ${Posts()}
            </div>
        </div>
        `;

        timelineModal.innerHTML = theContent;

        onModalClose();
    });
};

Any tips on how to achieve this?

Answer №1

One approach is to select an element using the getElementById method and then write a function to add data to the inner HTML of that element. You can try something like the example below:

var fruits = ["apple", "orange", "cherry"];
fruits.forEach(displayFruit);

function displayFruit(item, index) {
  document.getElementById("demo").innerHTML += index + ":" + item + "<br>";
}

Answer №2

Instead of using forEach, consider utilizing Array.map or declaring and initializing array variables to push elements into.

const newSlides = slides.map((el) => el)

Alternatively, you can also use:

const elements = [];
slides.forEach((el) => elements.push(el));
// Make sure to add a return statement in your arrow function as it currently does not return an element.
const Posts = () => {
    return slides.length > 0 &&
        slides
            .map((el) => {
                return <h2>123</h2>;
            })
            .join('');
};

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

Show more/less of the text snippet and main body of information

I am currently in the process of setting up a basic WordPress blog with only one page dedicated to the blog archive. However, I have encountered an issue. I want to implement a toggle functionality that allows visitors to easily navigate through posts on t ...

Discovering the row that was clicked: A step-by-step guide

Hello, I have created a table using JavaScript and now I am looking to determine the row and column that the user has clicked on. Below is the function I am using to generate the table: function doNextSteps() { removeAustriaFromCountries(); //i ...

Check the schedule for any upcoming events

I am currently designing a website for a friend and I have a question regarding the functionality of the FullCalendar jQuery plugin. Is there a way to determine if there is an event scheduled for today using FullCalendar? If so, I would like to display t ...

Ways to create a minimatch glob that selects every js file except those within a specific folder

I am currently facing a situation where I require a single glob pattern, utilizing minimatch, to match all JavaScript files except those in a specific directory. Unfortunately, the tool I am using does not offer any options such as an ignore glob, so a sin ...

Limiting Node.js entry with Express

I have a node.js script running on a server. I want to prevent it from being accessed directly from a browser and restrict access to only certain domains/IP addresses. Is this achievable? ...

Issue with Firefox pageMod addon: window.location not functioning properly

I'm developing a unique Firefox Add-on that implements page redirects based on keyboard input. The keyboard detection is functioning properly, however, the redirect functionality seems to be failing. The complete code can be found on GitHub (even thou ...

What could be causing my if statement to fail even though the condition is met?

I'm attempting to generate dynamic fields based on my chosen attributes. I have two array objects called addAttributes and fakeAttributes. The fakeAttributes contain the details of the selected attributes. I have a dropdown select component that displ ...

What is the most effective method for organizing an object by its values using multiple keys?

I'm interested in utilizing the sort method mentioned in the link but I am facing { "CYLINDER": 2986, "HYDRAULIC": 1421, "JACKS": 84, "INSTALLATION": 119, "REAR": 61, "JACK": 334, "TUBE": 1, "FEED": 114, "ASSEMBLY": 326, "DCS": 2 ...

Encountering difficulties running Angular application because of errors related to ɵɵinject and ɵɵdefineInjectable during compilation

Encountering this issue after running npm install: +-- UNMET PEER DEPENDENCY @angular/[email protected] +-- UNMET PEER DEPENDENCY @angular/[email protected] `-- [email protected] Getting this error after compiling: WARNING in ./node_mod ...

Is it possible to shuffle an array to a specific size in JavaScript?

Let's consider an array: array1 = [1, 2, 3, 4, 5, ........, 50] If we want to create a new array by randomly selecting elements from array1 with a specific length constraint, for example 5 numbers, the result could be: var arrayLength = 5 randomize ...

What is the best way to reference class variables and methods within a callback function in Typescript?

While working on my Angular project with the Highcharts API, I encountered a situation where I needed to pass a state code to a class level method after drilling down to a specific map location. Below is the snippet of my current code: ngOnInit() { this. ...

Placing an icon to the left of the primaryText within the <ListItem> component of Material UI

Seeking to enhance a <ListItem> from React Material UI that currently displays a checkbox on the left side. My goal is to insert an image or icon between the checkbox and the title, positioned to the left of the title. Upon reviewing the documentatio ...

Avoid repeated element IDs when using .push() in Angular

I am faced with a challenge involving an array of objects named users, defined in my component as users: Array<GroupUser> = [];. My objective is to verify that a new applicant does not have the same id as any existing user in the array. Below is the ...

Perform an action when a button is clicked in a VueJs single-page application

How can I trigger the refreshMailList function when clicking on the mail-list component? This is my Vue instance with a custom mail-list component: Vue.component('mail-list', { props: ['inboxmail'], template: ` <div> ...

Implementing file uploads with Bootstrap, jQuery, and Laravel

Looking to incorporate the blueimp jquery file upload feature into my Laravel app. Check it out here: https://github.com/blueimp/jQuery-File-Upload The form is set up and working properly with the plugin, but facing issues with creating server-side script ...

Resetting component state in React Native is essential for maintaining the correct

I need to reset the state of specific states without affecting others. When a button is clicked, the values of present_count, total_count, present, and total should all be restored to their original state (0), while keeping the state of subjects and text u ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...

The client end encountered an issue preventing the saving of a jpeg image

I have a situation where I need to retrieve an image stored on the server and send it to the client using sockets. While I am able to display the received image on canvas, I am encountering difficulties in saving the image to the local disk. I have attempt ...

Using the onreadystatechange method is the preferred way to activate a XMLHttpRequest, as I am unable to trigger it using other methods

I have a table in my HTML that contains names, and I want to implement a feature where clicking on a name will trigger an 'Alert' popup with additional details about the person. To achieve this, I am planning to use XMLHttpRequest to send the nam ...

The form will not pass validation

The validation of my form is not working correctly, as all my functions are called when the submit button is clicked. // Main Function function validate_form(form) { var complete = false; // Ensure that only one error message is displayed at a ti ...