2

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

This is my current div structure

<div class="input-wrapper">some text1</div>
<div class="input-wrapper">some text2</div>
<div class="input-wrapper">some text3</div>
<div class="input-wrapper">some text4</div>

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

<div class="form-group"><div class="input-wrapper">some text1</div></div>
<div class="form-group"><div class="input-wrapper">some text2</div></div>
<div class="form-group"><div class="input-wrapper">some text3</div></div>
<div class="form-group"><div class="input-wrapper">some text4</div></div>

I have used the following script

function create_structure(){
   $(".input-wrapper").append('<div class="form-group"></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

Owais Ahmed
  • 1,364
  • 1
  • 30
  • 62

2 Answers2

2

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 class="input-wrapper">some text1</div>
<div class="input-wrapper">some text2</div>
<div class="input-wrapper">some text3</div>
<div class="input-wrapper">some text4</div>
2

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 class="input-wrapper">some text1</div>
<div class="input-wrapper">some text2</div>
<div class="input-wrapper">some text3</div>
<div class="input-wrapper">some text4</div>

for your second Question about adding <span> you can achieve this by modifying my code to

$(".input-wrapper").each(function(i) {
   $(this).append("<span class='field-validation-valid'></span>");
   $(this).wrap("<div class='form-group'></div>");
});
Ben GG
  • 21
  • 4