Before each existing DIV in a loop, a new div is inserted using the insertBefore

const len = document.getElementById('parent').children.length
for (let i = 0; i < len; i++) {
const div =  document.createElement("div"); 
document.getElementById('parent').insertBefore(div, document.getElementById('parent').children[i])
}
<div id="parent">
  <div class="asfd"></div>
  <div class="xcbs"></div>
  <div class="msfd"></div>
  <div class="powg"></div>
  <div class="ksle"></div>
</div>

The output of this code is as follows:

<div id="parent">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div class="asfd"></div>
  <div class="xcbs"></div>
  <div class="msfd"></div>
  <div class="powg"></div>
  <div class="ksle"></div>
</div>

The goal here is to insert an empty div before each existing class.

<div id="parent">
  <div></div>
  <div class="asfd"></div>
  <div></div>
  <div class="xcbs"></div>
  <div></div>
  <div class="msfd"></div>
  <div></div>
  <div class="powg"></div>
  <div></div>
  <div class="ksle"></div>
</div>

After inserting the first empty div, it becomes the first child [0]. Is there a way to achieve the desired outcome? Thank you!

Answer №1

One reason for this behavior is that while iterating through elements, you are adding new ones which cause the length of the array to change:

1 - In the first loop, you add a div at index 0

2 - In the second loop, the element that was originally at index 0 is now at index 1 and you add a div before it

3 - This pattern continues...

Solution: Use a foreach loop (I used hr instead of div for better visibility without styles)

Array.from(document.getElementById('parent').children).forEach( (item, index) => {
const div =  document.createElement("hr"); 
document.getElementById('parent').insertBefore(div, item)
})
<div id="parent">
  <div class="asfd">asfd</div>
  <div class="xcbs">xcbs</div>
  <div class="msfd">msfd</div>
  <div class="powg">powg</div>
  <div class="ksle">ksle</div>
</div>

Answer №2

To address the issue of changing indexes, consider utilizing a querySelectorAll('#parent div') and looping through it using for..of rather than relying on an index-based loop:

for (const child of document.querySelectorAll('#parent div')) {
  document.getElementById('parent').insertBefore(document.createElement("div"), child);
}
#parent div[class] {
  background-color: red;
  height: 4px;
}

#parent div:not([class]) {
  background-color: yellow;
  height: 4px;
}
<div id="parent">
  <div class="asfd"></div>
  <div class="xcbs"></div>
  <div class="msfd"></div>
  <div class="powg"></div>
  <div class="ksle"></div>
</div>

Answer №3

This occurrence is due to the fact that

document.getElementById('parent').children
gives back a live collection of children, and
document.getElementById('parent').children[i]
will forever be
<div class="asfd"></div>
. Therefore, it is necessary to create a duplicate of
document.getElementById('parent').children
outside of the for loop:

const children = [...document.getElementById('parent').children];
for (let i = 0; i < children.length; i++) {
const div =  document.createElement("div"); 
  div.innerHTML = i;
document.getElementById('parent').insertBefore(div, children[i])
}
<div id="parent">
  <div class="asfd">asfd</div>
  <div class="xcbs">xcbs</div>
  <div class="msfd">msfd</div>
  <div class="powg">powg</div>
  <div class="ksle">ksle</div>
</div>

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

Error in Cordova Android Compilation ("unable to locate Build Tools version 24.0.1")

I'm currently experiencing some difficulties while trying to compile my Cordova project on Android. Upon entering the command "cordova build Android", I encountered the following error message: FAILURE: Build failed with an exception. * What caused ...

Navigate the conversation within the dialog without affecting the content below

Is it possible to have a dialog with scrollable content on top of a page that is also scrollable, but when trying to scroll inside the dialog using the mouse wheel, only the dialog body scrolls and not the page below it? What approach can be used to accom ...

Accessing variables within the controller's scope

Here is the JSON data I'm working with: { "id": "026001", "description": "Drop Forged Double Coupler", "CASHCUST01": { "hireRate": "0.01500", "saleRate": "2.50000" }, "SMITH00010": { "hireRate": "0.02500", "saleRate": "1.50000" }, " ...

Limit how API call costs are set in a function by throttling based on an argument

I am currently implementing express-throttle to restrict the number of API calls per IP address each day. I would like to dynamically set the 'cost' parameter in the 'options' array based on a value from the API request (refer to commen ...

Guide to creating varying component sizes using ReactJS and Styled Components

Is it possible to add variation to my button based on the prop 'size' being set to either 'small' or 'medium'? interface Props { size?: 'medium' | 'small'; } How can I adjust the size of the component us ...

The function signature '(newValue: DateRange<dateFns>) => void' does not match the expected type '(date: DateRange<unknown>, keyboardInputValue?: string | undefined) => void' as per TypeScript rules

I'm currently utilizing the MUI date range picker from https://mui.com/x/react-date-pickers/date-range-picker/. Here's my code snippet: <StaticDateRangePickerStyled displayStaticWrapperAs="desktop" value={valu ...

There appears to be a JavaScript validation error occurring on the current page, however, you are able

For my datepicker, I want an error message to display if the user selects a date more than 5 years in the future, saying "You are ineligible for our program". The user should not be able to proceed to the next step unless this error message is ad ...

Is there a way to exit from await Promise.all once any promise has been fulfilled in Chrome version 80?

Seeking the most efficient way to determine which server will respond to a request, I initially attempted sending requests in sequence. However, desiring to expedite this probing process, I revised my code as follows: async function probing(servers) { ...

What is the process for creating a global variable in JavaScript?

Having trouble changing the value of "invocation_num" within a loop? I attempted to modify it as follows, but ended up with an undefined value. Any help would be greatly appreciated. $(document).on("click", '.favoret', function(){ document ...

Exploring the process of linking multiple checkbox fields in a form with an ajax request

I have attempted the following method, but it is not working. I am able to retrieve the name from the form, but nothing gets assigned to the "sharewith" variable. My goal is to assign all selected checkboxes to one id called "sharewith" and then send them ...

Creating vibrant row displays in Vue.js: A guide to styling each row uniquely

I am not a front-end developer, so Vue and JS are new concepts for me. Currently, I am working on an application for managing sales. One of the components in my project involves displaying invoices in a list format. To make the rows visually appealing, I ...

Tips on creating a button that, upon clicking, triggers the download of an Excel file using PHPSpreadsheet

I am trying to figure out how to create a button that, when clicked, will download an Excel file named b1b5.xls with some specified values added. Here is the code I have so far: <html> <head> </head> <body> <center> < ...

The findIndex method is failing to retrieve the accurate index

The index returned by findeIndex in an express router function is incorrect. module.exports.nearestOffices = (req, res, next) => { Order.findById(req.params.idOrder).exec() .then(order => { return Promise.all([ Promise.resolve(or ...

Different time parameter for setting a timeout in Javascript

I am struggling to create a slideshow with varying time intervals for each image. My knowledge of Javascript is limited, and I have been working on resolving this issue for quite some time. /* function ShowEffect(element){ new Effect.Appear(element, ...

Create a fresh field for the form and store the data in the database

Issue Number One: I am looking to dynamically add a new field along with a button click event that will generate the new field. I attempted to use Jquery for this purpose, but as a newbie in this type of programming language, I am struggling. Can anyone o ...

The function canvas.toDataURL() is not recognized - error originating from a node-webGL wrapper

I am currently working on converting client-side volume rendering code in the browser to server-side rendering using pure JavaScript. On the server side, I am utilizing node-webgl. My objective is to send the server's canvas content to the client so ...

Issue with JavaScript not generating a header element within a specified div

function searchingFunction() { var searchInput = document.getElementById("searchbar"); if (searchInput.value != null) { var resultElement = document.createElement("h2"); resultElement.innerHTML = "Search results for " + searchInput.value; d ...

Enhance information flow within pages using SWR in NextJS

Utilizing SWR in a NextJS project has been a great experience for me. I have successfully fetched a list of data on my index page and added a new entry to the data on my create page. Now, I am looking to take advantage of SWR's mutate feature to updat ...

Convert checkbox choices to strings stored in an array within an object

I have a intricate object structure JSON{ alpha{ array1[ obj1{}, obj2{} ] } } In addition to array1, I need to include another array: array2 that will only consist of strin ...

Utilizing jQuery to send AJAX requests and display the results on separate lines within a textarea

My form includes a text area where users can enter keywords, one per line. I would like to implement the following functionality: upon clicking a button, an ajax request will be sent to the server to retrieve the result for each keyword entered. The resul ...