javascriptjquerywrapall

Moving multiple elements into new div


I want to move label, input and span elements inside the new div.

The structure is like this

<label for="" class="">First name</label>
<input id="fxb_8f3aee" class="form-control" type="text" value="" maxlength="255" placeholder="">
<span class="field-validation-valid" data-valmsg-replace="true"></span>

I want the label,input and span elements inside a new div like this

<div class="form-group">
   <label for="" class="">First name</label>
   <input id="fxb_8f3aee" class="form-control" type="text" value="" maxlength="255" placeholder="">
   <span class="field-validation-valid" data-valmsg-replace="true"></span>
</div>

I am able to move label inside the div using the following code

var el = $('.form-control');
$(el).add($(el).prev('label')).wrapAll('<div class="form-group"/>');

How can I also move the span element next to the input element (class = form-control) inside the form-group class div

I dont want to move all the elements. The HTML structure has few other hidden input and label elements. I just want to move the label above input[class=form-control] and the span below input[class=form-control] into a new div


Solution

  • This should do it:

    var el = $('.form-control');
    el.add(el.prev('label')).add(el.next('span')).wrap('<div class="form-group">');
    .form-group {background-color:pink}
    <script src="https://code.jquery.com/jquery-3.6.0.slim.js"></script>
    <label for="" class="">First name</label>
    <input id="fxb_8f3aee" class="form-control" type="text" value="" maxlength="255" placeholder="">
    <span class="field-validation-valid" data-valmsg-replace="true">span</span>

    There is no need for wrapping your el with $(), as it is already a jQuery object. Also, you can use the simpler .wrap() instead of .wrapAll() which is intended to be used for a nested wrapping of more than one layers. In your case you only wrap with one layer (<div class="form-group">).