adam78
adam78

Reputation: 10068

JQuery wrap span around elements

I have the following html markup:

<div data-type="checkbox" class="widget_type_checkbox">
 <div>
    <div class="helptext">help text</div>
    <div class="validationMessage" style="display: none;">Error message</div>
    <input id="widget_chk_I095Q7N6" type="checkbox" name="chk_I095Q7N6" required="" value="true" >
    <label for="widget_chk_I095Q7N6">My checkbox</label>
 </div>
</div>

For all checkboxes with class widget_type_checkbox I want to wrap the input and label inside a span as follows:

<div data-type="checkbox" class="widget_type_checkbox">
  <div>
    <div class="helptext">help text</div>
    <div class="validationMessage" style="display: none;">Error message</div>
    <span>
       <input id="widget_chk_I095Q7N6" type="checkbox" name="chk_I095Q7N6" required="" value="true" >
       <label for="widget_chk_I095Q7N6">My checkbox</label>
    </span>
 </div>
</div>
 

The following doesn't work:

$(".widget_type_checkbox").find("> div > span").not(":has(span)").find('input').next().andSelf().wrap('<span>');

Upvotes: 0

Views: 21

Answers (1)

User863
User863

Reputation: 20039

Using wrapAll()

  1. andSelf() deprecated, use .addBack() instead.

  2. wrap() wraps all elements separately, use wrapAll() instead.

  3. "> div > span" selector starts with > is invalid

$(".widget_type_checkbox :not(span) > input").each(function() {
  $(this).next().addBack().wrapAll("<span>")
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div data-type="checkbox" class="widget_type_checkbox">
  <div>
    <div class="helptext">help text</div>
    <div class="validationMessage" style="display: none;">Error message</div>
    <input id="widget_chk_I095Q7N6" type="checkbox" name="chk_I095Q7N6" required="" value="true">
    <label for="widget_chk_I095Q7N6">My checkbox</label>
  </div>
</div>

<div data-type="checkbox" class="widget_type_checkbox">
  <div>
    <div class="helptext">other help text</div>
    <div class="validationMessage" style="display: none;">Error message</div>
    <input id="widget_chk_I095Q7N7" type="checkbox" name="chk_I095Q7N7" required="" value="true">
    <label for="widget_chk_I095Q7N7">My checkbox</label>
  </div>
</div>

Upvotes: 1

Related Questions