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

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...

Is there a way to simulate Pinia and vue-i18n simultaneously?

Exploring Vue 3's Composition API with a twist: The store.ts file import { ref, Ref } from 'vue'; import { defineStore } from 'pinia'; export const useStore = defineStore('store', () => { const isLoading: Ref<bo ...

What could be causing the delay in Express when transitioning between console logs while using AngularJS $http.get?

By utilizing Express, Node, and Angular, I incorporated an HTML button on my website that triggers a get request to Express. This request then executes a function that logs a predefined message to the console. Initially, when I click the button for the fir ...

Steps to dynamically modify an HTML element within an Android WebView

https://www.bing.com/search?q=кму here I want to switch the bing icon to google I attempted : if (url == "https://www.bing.com/search?q=") { view.evaluateJavascript( ("\n"+ "wind ...

Having trouble reaching the elements stored in an array?

As a beginner in Angular and JavaScript, I may be making some obvious mistakes so please bear with me. I have written this code that allows the selection of 2 text files and then combines them into a single array. $scope.textArray = []; $scope.textUpload ...

Newbie React Developer Struggling to Implement Material-UI Example in React Project, State Functioning Differently from Hooks

I am currently in the early stages of learning React and trying to create a form for a project management web application. For this, I am using material-ui library. I referred to one of the select box component examples from the material-ui documentation ...

"Getting Started with Respond.js: A Step-by-Step

I've been struggling to find clear instructions on how to properly set up respond.js. Should I just unzip it into the htdocs folder, or do I only need respond.min.js in there? Then, do I simply reference the file like this... <script src="respon ...

What is the best way to manage a group of checkboxes using EJS?

I am currently utilizing ejs for my website pages and on one particular page, I have an array of objects. The number of objects in the array is not known when the page initially loads. This page allows me to edit a series of announcements and I would like ...

Using curly braces when invoking a function from HTML within a Vue.js application

When I call a function, for example on click, it works whether or not I use curly braces. However, I have created a function that triggers a custom event from a child component. I then await this event in a parent component and update the state with my par ...

The basic node API request is not showing any information

There is a request in my server.js file var Post = require('./../models/post'); //GET ALL POSTS app.get('/api/posts', function (req, res) { Post.getPosts(function (err, posts) { if(err) { throw err; } ...

Unable to employ Javascript while utilizing AJAX within jQuery Mobile

Exploring the potential of Swiper Javascript Api from within Jquery Mobile raises some challenges. The compatibility issues with Ajax in Jquery Mobile complicate the execution of Javascript functions. This becomes evident when examining example source cod ...

Importing .js files from the static folder in Nuxt.js: a step-by-step guide

I'm in the process of transitioning my website, which is currently built using html/css/js, to Nuxt.js so that I can automatically update it from an API. To maintain the same website structure, I have broken down my code into components and imported ...

Is it possible to compare every element in an array with one another using an asynchronous process in NodeJS?

I am currently utilizing Resemble.js for image comparison within my web application. I have an array of image URLs that I need to compare with each other in order to calculate a unique score for each image. For example: [url1, url2, url3, url4] The minimu ...

Issue with Material UI Textfield functionality on mobile Safari browser

UPDATE: Resolved the problem by including this code in index.css input { -webkit-user-select:text;} In my application, I am using a Material UI box that contains text fields with an onChange handler. While the TextFields function correctly on most bro ...

Issue encountered with search.run().getRange function when accessing a stored search in suitescript 2.0

I am facing an issue with my saved search in the beforeLoad userevent script. After adding a filter and running the search, Netsuite throws an UNEXPECTED_ERROR. Any ideas on what might be causing this error? var poRec = context.newRecord; var countIt ...

Is it feasible to invert the order of arguments in async.apply?

According to the async documentation: apply(function, arguments..) Creates a function continuation with certain arguments already applied. This can be useful when combined with other control flow functions. Any additional arguments passed to the returned ...

What does the "listen EACCESS localhost" error in the code signify and why is it occurring?

const express = require('express'); const morgan = require('morgan'); const host = 'localhost'; const port = 3000; const app = express(); app.use(morgan('dev')); app.use(express.static(__dirname + '/public&ap ...

The initial time delay set by setTimeout does not seem to have any impact

The issue with setTimeout not working as expected lies in its execution order. The code below it gets executed without waiting for the delay specified in the first argument of 'setTimeout' to run. (function() { var a = ['#bird',&ap ...

Place the div absolutely on top of the Flash content

Can a <div /> be absolutely positioned over a Flash banner without including wmode="transparent" in the banner? I am trying to display a lightbox above my ads, but I cannot make changes to the banners since they are provided by a third party. Edit: ...

Convert an array comprising arrays/objects into JSON format

This problem is really challenging for me. The structure of my array goes like this: array1 = [ [array2], [array3], [array4] ... [array17] ] array2 = [ ['obj1'], ['obj2'], ['obj3'] ... ['obj30'] ] ... ... obj1 = ({p ...