during array iteration, the appendChild function is only executed once

Here's a simple question for all of you:

So, I've got this for loop:

var pNewTag = document.createElement('p');
var grabWrapper = document.querySelector('.footerInfo');
var myArray = grabWrapper.children;

 for ( var i = 0; i < myArray.length; i++ ) {
   grabWrapper.children[i].appendChild(pNewTag);
   pNewTag.innerHTML = " this works ";
 }

The length of the array I'm using is 7, but the appendChild function within the loop only executes once. I want it to run on each iteration. Any ideas on what I'm overlooking?

Answer №1

The reason for the issue is that you are manipulating a single element instead of creating separate elements for each iteration.

var grabFooter = document.querySelector('.footerInfo');
var footerChildren = grabFooter.children;

for ( var i = 0; i < footerChildren.length; i++ ) {
   var newParagraph = document.createElement('p');
   newParagraph.innerHTML = " this solution ";

   grabFooter.children[i].appendChild(newParagraph);
}

Answer №2

In order to achieve this, you will need to generate several p elements:

var footerInfo = document.querySelector('.footerInfo');
var childElementsArray = footerInfo.children;

for ( var i = 0; i < childElementsArray.length; i++ ) {
    var newPTag = document.createElement('p');
    newPTag.innerHTML = " this is effective ";
    footerInfo.children[i].appendChild(newPTag);
}

It is advisable to populate the element before inserting it into the document. By following this approach, your browser will avoid reflowing the document twice.

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

jQuery fails to execute in ajax success function

Currently, I am using jQuery and Ajax to dynamically populate a select element. However, I am facing an issue within my success callback where my DOM manipulation is being ignored. An interesting observation is that even though my console.log('test&a ...

How can I activate JQUERY when an event occurs?

I am trying to create a selection box where, upon clicking an item on the left, it will shift automatically to the right. However, I am facing issues with using triggers to achieve this functionality. Here is the code I have written. <script type="te ...

Is using async/await with setState() in React.js the best approach for handling asynchronous operations?

By utilizing async and prevState, I found a solution to console.log the correct state of the page immediately after updating it. As I delved into backend development, I took the time to understand how async operations function. This led me to experiment w ...

Calculating the total number of days in each month within a specified date range using PHP in a dynamic way

Thank you for taking the time to help me with my issue. For instance, if a user selects a date range from 10 Dec 2016 to 20 April, how can I calculate the number of days for each month within that range? For example, Dec=22 Days, Jan=31 Days, Feb=28 Days, ...

What could be the reason for my error messages not displaying when I have defined them on a static method in the schema, despite the error handling seeming to

I have created a static method in my schema that defines the User document structure in my MongoDB database. This method, .findByCredentials(), is used to verify if a user-provided email and password match an existing user and hashed password in the databa ...

Utilizing the Jquery hover feature to reveal or conceal an element

My Hover function is designed to display and hide sub menus when a person hovers on them. The issue I'm facing is that the menu disappears when I move the mouse down towards it. Can someone help me identify what I am doing wrong here? ...

Creating Lists dynamically in Java without any duplicates can be achieved by using a HashSet to store

When looking at a similar question like How to dynamically create Lists in java?, I found that I have a very similar issue to the one asked by another individual. Within my project, I am working with airplanes, airports, and passengers for PNR records. T ...

Utilizing a switch case for typing

I am working on a React component that takes in a list and a type as props. The list is an array of objects, while the type is an optional enum string. Inside this component, there is a function that uses a switch case statement to enforce a specific type ...

Embark on a journey through a preorder traversal of a Binary Tree using TypeScript

Hello! I've been tasked with creating a function that iterates over a binary tree and returns all its values in pre-order. Here is the code snippet: interface BinTree { root: number; left?: BinTree; right?: BinTree; }; const TreePreArray ...

Toggling the visibility of divs in a dynamic layout

How can I use JQuery/JavaScript to show only the comment form for a specific post when a button or link is clicked on a page containing multiple posts divs with hidden comment forms? <div class="post"> <p>Some Content</p> <a ...

Using TinyMCE from within a PHP function only displays a basic textarea box

My experience with TinyMCE has been smooth when using it from a single php script. However, I encountered an issue when trying to include it on my website through a PHP function - only a blank textarea box appeared. After numerous tests, I realized that th ...

Updating Angular to switch out the HTML content with a direct hyperlink to a specific section within a

A particular component on my website displays comments that contain HTML formatting, including a footer with information such as the author's name and date. I want to enhance this by turning the contents of the footer into clickable anchor links that ...

Clear the div content when submitting the form

I have a search bar for ISBN numbers and a submit button. When the form is submitted, the results are displayed in a div below the form, which works fine. However, my problem arises when I can repeatedly press submit and multiple divs appear one after ano ...

Converting a JSON string into a JavaScript array

I am dealing with a large collection of 235 JSON strings structured like this: "57": { "ID": 6986, "Town": "Paris", "latitude": 48.8829447, "longitude": 2.3453532999999 }, "58": { "ID": 6987, "Town": "Paris", "latitude": 48.874 ...

What is the best way to handle mapping an array with uncertain levels of nesting?

My task involves rendering an array of comments in ReactJs, each of which can have nested comments at unknown levels. I am struggling to figure out how to display these comments with their respective nesting levels. comment 1 -- comment 2 -- comment 3 --- ...

The HTTP GET request was successful, however, there is no data being displayed on the screen

I am currently facing an issue with fetching data from a web server. The data is retrieved successfully as I can see the object in the console log, but it does not render in the component template. export class CountrydetailsComponent implements OnInit { ...

Angular 2 sidebar icons appearing vertically instead of in a row

Greetings! I've been struggling for hours to display a sidenav using Angular 2, with links listed as rows. Here is what my current setup looks like: https://i.sstatic.net/fmmAR.jpg Here is the code I've been working on: <md-sidenav-containe ...

Utilizing the current state within a React callback function closure: A guide to maximising efficiency

I'm currently working on a web page that features a dynamic list of form inputs. Users have the ability to add or remove input fields using designated buttons. To manage this functionality, I've created a parent object called <Ingredients /> ...

Which is more memory efficient: creating an object with functions defined on it using a function, or creating an instance of a class?

Imagine if I were to create a hypothetical class (this is purely for demonstration purposes) class X { constructor(word, number) { this.wordNumberString = word + number; } saySomething() { return `${this.wordNumberString} ${this.wordNumberStr ...

Extracting information from the fileuploadfield in Ext JS 3

Currently utilizing Ext.ux.FileUploadField within Ext JS 3.3.1. Aiming to retrieve the file data from the form without having to submit it. Wondering if anyone has insight on whether this is feasible. Currently able to view the filename but not the actual ...