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

When Controller Scope Goes Missing in ng-repeat

Upon glancing at my code, it should be evident that I am a newcomer to the world of Angular. I am currently developing an application that enables users to search for text, queries a database whenever the value in the text input changes, and displays a li ...

What is the best way to dynamically showcase options in a React application?

product.js Qty: <select value={qty} onChange={(e) => { setQty(e.target.value) }}> {[...Array(product.countInStock).keys()].map((x) => ( <option key={x + 1} value={x + 1}> ===> I need to dynamically display options b ...

Bidirectional enumeration in TypeScript

I am working with an enum defined as: enum MyEnum { key1 = 'val1' key2 = 'val2' } However, I am unsure how to create a SomeType implementation that fulfills the following requirements: Function: const myFunction = (param: SomeT ...

How to verify changes in session variable using PHP and AJAX

Hey there! I'm looking for a way to continually monitor changes in a session variable within PHP. Let's say the session variable "x" starts off with a value of "1" and then, after five seconds, it changes to "2". This session variable "x" is up ...

Dynamic reloading of a div with form data using jQuery's AJAX functionality

I am currently developing an online visitor chat software using PHP and MySQL. My goal is to load the page when the submit button is clicked. Submit Button ID: send Visitor ID: vid Chat ID: cid Below is the snippet of code for an Ajax request that I hav ...

Complete API Integration with Diverse Models for Android Development

Having trouble grasping some concepts about Rest API's. I successfully created 2 apps using JSON and POJO, where I had a large JSON file that allowed me to utilize Retrofit and move forward with the app. However, today I face a new challenge. I am tr ...

React Side Panels that Collapse and Expand

Apologies if this task seems simple, as I am new to transitioning to React. My current application is primarily built with JavaScript, CSS, and HTML, and I am now looking to migrate it to React. There is a full-length horizontal side panel that is initiall ...

Tracking the referral source when the email box is clicked

document.referrer is a JavaScript method that returns the URI of the page that linked to the current page. If the user navigated directly to the page, for example through a bookmark, the value returned by document.referrer will be an empty string. You can ...

jQuery - Enlarge Tree View to the level of the selected node

I am struggling to figure out how to expand the tree view up to a selected node level. If anyone has any ideas on how to accomplish this, please let me know. For instance, if we click on 'Parent d' in the 'Category list', I want to exp ...

Guide to building a hierarchical data object with JavaScript

Prior This object consists of multiple rows: { "functions": [ { "package_id": "2", "module_id": "2", "data_id": "2" }, { "package_id": ...

Animating elements within a D3.js force layout

I am looking to create a unique data visualization that resembles floating bubbles with text inside each bubble. Currently, I have a prototype using mock data available here: JSfiddle // Here lies the code snippet // ... However, my current challenge li ...

What is the reason behind one function triggering a re-render of a component while the other does not in Next.js?

I am currently working on a Next.js web application where one of the pages contains two functions that utilize useState() to add or remove emails from an array. const [invites, setInvites] = useState([]) // other code const lmao = () => { console.lo ...

Utilize Sequelize to enclose a column with double quotation marks in a where clause

I am working with a JSONB column in my database. My goal is to make a query to the database where I can check if a specific value in this JSON is true or false: SELECT * FROM table WHERE ("json_column"->'data'->>'data2')::boo ...

Can the second function be modified to incorporate the first one's syntax?

export const composeValidators = (...validators) => value => validators.reduce((error, validator) => error || validator(value), undefined); export const composeAccreditionValidators = (...validators) => value => validators.reduce((error, va ...

Having trouble setting cookies with Node.js Express?

Check out this code snippet: const app = express(); const cookieParser = require('cookie-parser'); app.use(cookieParser()); app.post("/pinfo", (req, res) => { var form = new formidable.IncomingForm(); form.parse(req, async functi ...

Issue with MVC 4 C# - Implementing column chart visualization using json object in Google chart

In my MVC 4 application using C#, I'm incorporating the Google Visualization API column chart to display data graphics. However, recently I've been facing a bug that affects the visualization of the information despite the data being correct. He ...

Deactivate checkbox based on dropdown selection

I'm facing an issue where I need to disable a checkbox when a certain option is selected from a dropdown inside a datatable in my xhtml file. The dropdown has options like L, C, UV, and more, and when "L" is chosen, the checkbox should be disabled. B ...

Convert a comma-delimited string containing a numerical value into a floating point number, for example, 3.00

I need to extract a number from a value that is returned with commas around it. My goal is to convert this value into a number so that I can compare it against another number in my code later on. However, I'm facing difficulties in reliably extracting ...

Transfer the contents from the text box field into the <p> tag

I know how to transfer text from one textbox to another in JS, but I'm interested in moving the text from a textbox to a paragraph. Can anyone explain how to achieve this? Thank you Update: Apologies for not being more specific earlier. I'm att ...

What is the best way to include a background image in a div within a React component?

I'm currently following a tutorial on creating an RPG game using React. The tutorial can be found at this link. I am trying to replicate the presenter's code by typing it out myself. However, I'm running into an issue when attempting to add ...