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!