Using the power of JavaScript to iterate through elements with the

Looking for a way to integrate JSON data into your simple bootstrap page? Here's a script that might help:

Take a look at the following script:

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState === 4 && xhr.status === 200) {
        var tweets = JSON.parse(xhr.responseText);  

        var tweet = '   <div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">';
        var name = ' <h4 class="card-title">';
        var photo = '    <div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">';

        for (var i = 0; i < tweets.length; i += 1) {

            name += tweets[i].name;
            name += '</h4> </div>';

            tweet += ' <div class="jumbotron">';
            tweet += '  <p  class="card-text">';
            tweet += tweets[i].tweet;
            tweet += "<br>";
            tweet += "</p></div></div>";

            photo += '  <img class="img-responsive img-circle" src="user/';
            photo += tweets[i].activation;
            photo += '/';
            photo += tweets[i].pic;
            photo += '"></div></div>';

            document.getElementById('photo').innerHTML = photo;
            document.getElementById('name').innerHTML = name;
            document.getElementById('tweet').innerHTML = tweet;

            // close all html tags   
        }
    }
};
xhr.open('GET', 'empdata.json');
xhr.send();

Additionally, here is an example of how you can structure your HTML:

<div class="container">
    <div class="card">
        <div class="card-header">    
            <div class="row">
                <div id="photo">
                    <!-- The picture will be displayed here -->
                </div>
                <div id="name">
                    <!-- The name will be displayed here -->
                </div>
            </div>    
            <div class="card-block row">
                <div id="tweet">
                    <!-- The tweet will be displayed here -->
                </div>
            </div>
        </div>
    </div>
</div>

<div class="card-block row">    
    <div id="tweet"> </div>
</div>

While the loop correctly cycles through all the JSON data, it seems to display pictures first, followed by names, and then finally the tweets as separate entities. It could be related to the looping mechanism being used.

Answer №1

It appears that a more concise solution could be implemented, while keeping the existing HTML structure intact. Here is one approach:

var container = document.querySelector(".container");
for (var i=0; i<tweets.length; i += 1) {
    var name = ' <h4 class="card-title">';
    name += tweets[i].name;
    name += '</h4> </div>';
    var tweet = '<div class="col-xs-12 col-sm-6 col-md-8 col-md-offset-3">'
    tweet += ' <div class="jumbotron">';
    tweet += '  <p  class="card-text">';
    tweet += tweets[i].tweet;
    tweet += "<br>";
    tweet += "</p></div></div>";
    var photo ='<div class="col-md-4 col-md-offset-3"><div class="col-md-4 ">' 
    photo += '  <img class="img-responsive img-circle" src="user/';
    photo += tweets[i].activation;
    photo += '/';
    photo += tweets[i].pic;
    photo += '"></div></div>';

    container.innerHTML+='<div class="card"><div class="card-header">'+
    photo+name+tweet+'</div></div>';
}

Answer №2

UPDATED Make sure to place innerText assignment outside of the loop for optimized performance.

for (var i=0; i<tweets.length; i += 1) {

        name += tweets[i].name;
        name += '</h4> </div>';
              ...
        photo += tweets[i].pic;
        photo += '"></div></div>';

    }
        document.getElementById('name').innerHTML = name;
        document.getElementById('photo').innerHTML = photo;

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

JavaScript with dropdown menus

Currently, I am in the process of implementing a JavaScript code snippet that will be triggered when a checkbox is checked. Once the checkbox is checked, the form should display two additional select boxes. My attempt at coding this functionality was not ...

Creating an HTML5 video tag with bearer authentication using a WebAPI: The ultimate guide

My ASP.NET WebAPI requires bearer authentication, and most of my requests towards the API follow this format: GET http://localhost:29080/api/v1/users/me HTTP/1.1 Host: localhost:29080 Connection: keep-alive Accept: application/json, text/plain, */* Origin ...

Node.Js Web Scraping: How to Extract Data from JavaScript-Rendered Pages Using Request

I am looking to extract specific content from Google search results that is only visible in browsers, potentially due to Javascript being enabled. Specifically, I am interested in scraping the Knowledge Graph "People also search for" information. Currentl ...

Efficiently handle user authentication for various user types in express.js with the help of passport.js

Struggling to effectively manage user states using Passport.js in Express.js 4.x. I currently have three different user collections stored in my mongodb database: 1. Member (with a profile page) 2. Operator (access to a dashboard) 3. Admin (backend privi ...

Deactivating a form field depending on a selected radio button in Angular 2

If I have two radio buttons, with a click function called localClick for the first button to give value 1 and the second button to give value 2. <div class="ui-g-12"><p-radioButton name="group1" value="Local" (click)=localClick(1) label="Local"&g ...

Utilizing Promise.all to update subdocuments with Mongoose

Encountered an error while checking the value in promiseArr, seeking assistance or suggestions for a better approach. Thanks! **Error** <rejected> { MongooseError: Callback must be a function, got [object Object] at new MongooseError (D:\P ...

a new approach for creating a conditional function in pointfree fashion

Can someone help me convert this code into a pointfree style? To provide context: The function receives an Array of Either types and returns a Task type. If any of the Either types have the left set, the Task type is rejected with that value. If none of t ...

Ways to determine if a new set of input values duplicates previous rows in an array

My form has an array of input fields. Is there a way to validate each row's inputs and ensure that they all have at least one unique value in any field, preventing identical rows? For example, the 2nd row should only be allowed to have a maximum of ...

The error message states: "change is not defined"

I am encountering an issue where I have 4 input boxes triggering a function on keyup using the onkeyup event. Strangely, I keep receiving an error stating that "change" (the function's name) is not defined. Despite correctly defining the function, I c ...

Updating a JSON file with new object using node.js

Currently, I am attempting to insert a single object into an extensive JSON file. My approach involves parsing the entire file using FS and JSON.Parse, adding the new JSON object in memory, and then rewriting the file. While I am aware of FS's append ...

`Can a creation of this nature be accomplished?`

In my text input field, users can type messages to send to me. I'd like to add buttons on the page with symbols like "!", "XD", and "#". When someone clicks on a button, such as the "!" button, that corresponding symbol should be inserted into the tex ...

listening for events on nested classes

I am looking to dynamically toggle the class "collapsed" on each element with the class "category" when it is clicked. The issue arises when these "category" elements are nested within each other, causing the child elements to also trigger the class change ...

AssistanceBubble.js with ASP.NET UpdatePanel

Looking for guidance on implementing HelpBalloon.js () within an ASP.NET UpdatePanel. Experiencing issues with image loss after a postback. ...

Conceal and unveil stationary navigation when scrolling back to the very top of the screen

My current setup includes a navigation that dynamically hides as the user scrolls down and reappears when scrolling up. Additionally, I have applied the class .fixed on #top-wrapper to alter the layout/styling of this specific div. However, I am facing dif ...

Include a new route in the Vue.js router dynamically during runtime

I am in the process of developing an application and I want to incorporate extensions into it. These extensions will have their own Vue components, views, and routes. Instead of rebuilding the entire app, I am looking for a way to dynamically add these new ...

Searching for a specific value in a JSON object using a variable in Python

json file 1 [{'one.10': 'eno', 'three': 1, 'two': False}, {'one.21': 'eon', 'three': 2, 'two': True}, {'one.31': 'noe', 'three': 3, 'two&apo ...

`Issues with AJAX PHP file upload`

I've been working on an AJAX PHP upload script, but I'm facing some issues. Once the user selects an image to upload, it should display in the specific div container specified in my javascript file (which is working fine). However, I believe ther ...

Is it possible to implement sticky sessions with Node.js and pm2?

Can sticky sessions be implemented using the pm2 node module? Although not supported by Node.js's internal cluster module on purpose, it could still prove beneficial in scenarios like paused media streams. ...

Is it possible to implement a Promise.some() function that includes a timeout

Scenario - collect multiple URLs and cache the responses. URLs that are processed quickly (e.g. within 500ms) are included in the current pass, while those that take longer are still cached for use in the next round (approximately 10 minutes later in our a ...

My div does not refresh when using .load

I implemented ajax to retrieve the start time and end time from another page, and used setInterval to call this function every second like so. setInterval(function () { CheckTime() }, 1000); function CheckTime() { $.ajax({ url: "Get_TIme. ...