Creating an element in JavaScript with a designated ID is a

I'm working on creating a JavaScript array that holds 3 elements:

var employees =
    [
        {"firstName":"John", "lastName":"Doe"},
        {"firstName":"Anna", "lastName":"Smith"},
        {"firstName":"Peter", "lastName":"Jones"}
    ]

To iterate through the data using a for loop, you can use the following code:

for (let i = 0; i < employees.length; i++)

If you want to create a new <p> element for each object and populate it with the data, you'll need to assign an id to each <p>. Here’s how you can do that:

This is what your current code looks like:

<!DOCTYPE html>
<html>
    <body>
        <h2>JSON Java Syntax Examples</h2>

        <script>
            var employees =
                [
                    {"firstName":"John", "lastName":"Doe"},
                    {"firstName":"Anna", "lastName":"Smith"},
                    {"firstName":"Peter", "lastName":"Jones"}
                ]

            for (let i = 0; i < employees.length; i++)
                {
                    document.createElement("p");
                    document.getElementById(i).innerHTML = employees[i].firstName + " " + employees[i].lastName;
                }
        </script>
    </body>
</html>

Answer №1

  1. Swap out the use of int with var when defining your for loop.
  2. Assign a new element to a variable, such as new_p.
  3. Utilize the textContent() function to set the text content for your element.
  4. Lastly, append the newly created paragraph (new_p) to your body using the appendChild() function.

I hope this explanation is helpful!


Code Snippet Example

var employees =
    [
      {"firstName":"John", "lastName":"Doe"},
      {"firstName":"Anna", "lastName":"Smith"},
      {"firstName":"Peter", "lastName":"Jones"}
    ]

for (var i = 0; i < employees.length; i++)
{
    var new_p = document.createElement("p");

    new_p.textContent = employees[i].firstName + " " + employees[i].lastName;

    document.body.appendChild(new_p);
}

Answer №2

Upon reviewing the feedback and answers provided here, as well as conducting further research, I have successfully identified a solution that works impeccably. In this case, I opted not to assign an ID to any of the newly generated elements. Instead, I utilized innerHTML to insert the data into the element, followed by using appendChild to attach the tag to the document.

Below is the operational code snippet:

<!DOCTYPE html>
    <html>
        <body>
            <h2>JSON Java Syntax Examples</h2>

            <script>
                var employees =
                    [
                        {"firstName":"John", "lastName":"Doe"},
                        {"firstName":"Anna", "lastName":"Smith"},
                        {"firstName":"Peter", "lastName":"Jones"}
                    ]

                for (var i = 0; i < employees.length; i++)
                    {
                        var p = document.createElement("p");
                        p.innerHTML = employees[i].firstName + " " + employees[i].lastName;
                        document.body.appendChild(p);
                    }
    //            document.getElementById("demo").innerHTML = employees[0].firstName + " " + employees[0].lastName;
            </script>
        </body>
    </html>

I sincerely appreciate all the valuable responses!

Answer №3

Let's take a more contemporary approach:

To start, we can define a function that generates a DOM document fragment using an array of elements. This fragment can be assembled and added to the DOM in one step. While this may seem unnecessary for a simple scenario, it can significantly improve performance when dealing with numerous DOM manipulations.

function createDocumentFragment(arr) {
  return arr.reduce((r, e) => {
    r.appendChild(e);
    return r;
  }, document.createDocumentFragment());
}

Next, let's create a function that transforms an individual employee's data into a p element:

function createEmployeeElement(emp) {
  var text = document.createTextNode(emp.firstName + ' ' + emp.lastName);
  var p = document.createElement('p');
  p.appendChild(text);
  return p;
}

Now that we have these functions set up, all we need to do is:

document.body .                 // Add
  appendChild (                 // append
    createDocumentFragment (    // the fragment containing
      employees .               // all employees
        map (                   // transformed into
          createEmployeeElement // DOM elements
)));

Answer №4

Give this code a try:

        Iterate through the employees array and create a paragraph element for each employee's full name:
        
        for (int i = 0; i < employees.length; i++)
            {
                var pObj = document.createElement("p");
                var t = document.createTextNode(employees[i].firstName + " " + employees[i].lastName); 
                pObj.appendChild(t);
                document.body.appendChild(pObj); 
            }

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

Activate a button with jQuery when a key is pressed

Currently, I have two buttons set up with jQuery: $('#prev').click(function() { // code for previous button }); $('#next').click(function() { // code for next button }); My goal now is to implement a .keypress() handler on the ...

A step-by-step guide on implementing ng-annotate to your code

Is there a way to run ng-annotate through the command line? I am attempting to combine and minify Angular, Angular Routes, and my own script.js into one file. When I use grunt uglify:app1, I encounter an injection error. While my code successfully minifies ...

What could be causing the issue preventing me from updating my SQL database through AJAX?

$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'functions/delivered.php', data = {'action': clickBtnValue}; $.post(ajaxurl, da ...

The class styling is malfunctioning

When I click the 'night' button, I want the word color in the class=css to change to white. However, this is not working as intended, even though all other word colors are changing correctly. Here is my code: .css { font-weight: bold; ...

Encounter a critical issue while making a JSON request using Kendo UI

I am facing an issue at my workplace where I need to integrate Angular.js with ASP.NET MVC. Currently, I am trying to build a simple application that features a Kendo UI grid on the front page. In my App.js file, I am fetching data from the Data Controller ...

Real-time chart updates through REST API integration with JavaScript

I am searching for a JavaScript library that is capable of creating line charts and making calls to a REST API every few seconds (such as 5s or 3s) in order to update the line chart dynamically. I have found some libraries that support live chart updatin ...

Switching the visibility of multiple textareas from block to none

I am currently exploring ways to make one text area disappear while another one appears in its place. With limited knowledge of Javascript and just starting my journey into HTML and CSS, I am reaching out to the forum for assistance or guidance on the rig ...

How can you run a function in JavaScript or TypeScript that is stored as a string?

Is there a way to call a function that is stored as a string? For example: var dynamicFun = `function Hello(person) { return 'Hello' + person; }` In this case, the dynamicFun variable can store any function definition dynamically, such as: var ...

The error message states that the property "user" is not found in the type "Session & Partial<SessionData>"

I recently had a javascript code that I'm now attempting to convert into typescript route.get('/order', async(req,res) => { var sessionData = req.session; if(typeof sessionData.user === 'undefined') { ...

Unknown custom element error in Laravel and Vuetify

I encountered errors in my Laravel project, specifically with custom elements like this. [Vue warn]: Unknown custom element: <v-app> - did you register the component correctly? For recursive components, make sure to provide the "name" option. found ...

What is the process for combining and compressing an Angular 2 application?

I am currently trying to concatenate and minify an angular2 application. My approach so far involved concatenating all my *.js files (boot.js, application.js then all components) into one file and injecting it into my index.html. I also removed the <s ...

Combining the power of ExpressJS with a dynamic blend of ejs and React for an

My current setup involves a NodeJS application with an Express backend and EJS for the frontend. The code snippet below shows an example route: router.get("/:name&:term", function(req, res) { Course.find({ courseName: req.params.name, courseTerm: req.p ...

A guide on updating the color of a Button component (Material UI) when dynamically disabling it

In a React table, I have a button that is disabled based on the value in an adjacent column. For example, if the value in the adjacent column is "Claimed", the button is disabled. However, if the value is "Failed" or blank, the button can be clicked. Curre ...

Converting a List of Maps from Immutable.js into a List of Lists and utilizing it as the dataset for Google Charts

I am currently working on implementing the Google Charts library to visualize some time series data. Right now, I have dummy data stored in a separate file from my application. In this file, I have an Immutable List structured like this: le ...

What is the best way to insert a new row into a table upon clicking a button with Javascript?

Hi everyone, I'm facing an issue with my code. Whenever I click on "Add Product", I want a new row with the same fields to be added. However, it's not working as expected when I run the code. Below is the HTML: <table class="table" id="conci ...

Show or hide the legend on a highchart dynamically

I am currently utilizing highchart in my application and I am interested in learning how to toggle the visibility of the legend within the highchart. Here is what I have attempted: var options = { chart: { type: 'column&a ...

Having trouble retrieving data values from methods within my Vue.js component

I am having trouble accessing the lat and lng values from the data() method within the maps() method. Here is a link to my Vue.js component code: https://gist.github.com/melvin2016/c8082e27b9c50964dcc742ecff853080 Here is an image of the console showing ...

Connecting factors

Let me simplify what my code does: var list = { "group":{ "subgroup1":[{"name1":"Jimmy","name2":"Bob"}], "subgroup2":[{"name1":"Sarah","name2":"Nick"},{"name1":"Kevin","name2":"George"}] } } function group(group,name){ var link ...

Ways to retrieve the name of a JValue object

I have been working with Newtonsoft.Json to parse Json text, and I am trying to find a way to retrieve the name of a JToken or JValue object. For example, if "ChoiceId":865 is the value, I need to extract "ChoiceId". Despite spending hours on it, I haven&a ...

The functionality of JQuery TableSorter is not responsive when a user clicks on it

I seem to be running into an issue on my website where I can't get the JQuery TableSorter to work properly. When I attach it to a table for sorting, nothing happens when I click on the headers. The table remains static and unsortable. Here's a s ...