Home > Mobile >  Create a new div and move the existing div
Create a new div and move the existing div

Time:06-08

I have to create a new div and move the existing div into the newly created div.

This is my current div structure

<div >some text1</div>
<div >some text2</div>
<div >some text3</div>
<div >some text4</div>

I want to create a new div <div ></div> and move the input-wrapper div inside. So the new structure should look like this

<div ><div >some text1</div></div>
<div ><div >some text2</div></div>
<div ><div >some text3</div></div>
<div ><div >some text4</div></div>

I have used the following script

function create_structure(){
   $(".input-wrapper").append('<div ></div>'); 
   $(".form-group").appendTo(".input-wrapper");      
};
window.setTimeout( create_structure, 2000 ); // 2 seconds

I am not getting the desired structure.

Anything I am missing in the code?

Any suggestions would be appreciated. Thanks in advance

CodePudding user response:

how about using wrap method in jquery?

for (let i = 0; i < $(".input-wrapper").length; i  ) {
    $($(".input-wrapper")[i]).wrap("<div class='form-group'></div>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >some text1</div>
<div >some text2</div>
<div >some text3</div>
<div >some text4</div>

CodePudding user response:

Use the build-in .each in JQuery :

$(".input-wrapper").each(function(i) {
   $(this).wrap("<div class='form-group'></div>");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >some text1</div>
<div >some text2</div>
<div >some text3</div>
<div >some text4</div>

  • Related