简体   繁体   中英

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>');

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM