Skip to content

Instantly share code, notes, and snippets.

@BigglesZX
Created December 19, 2010 17:17
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save BigglesZX/747490 to your computer and use it in GitHub Desktop.
Save BigglesZX/747490 to your computer and use it in GitHub Desktop.
Wrap two adjacent elements in a containing div using jQuery
This is a useful trick if you want to wrap two sibling elements in a containing element, for example to fix stupid float bugs in IE7. I had a bit of a time figuring out how to select the right elements (wrapping is easy enough with one element, or one element's children), so I thought I'd share for the Greater Good.
From markup like this:
<div class='form-container'>
...
<div class='form-label'>Name (required)</div>
<div class='form-field'><input type="text" name="you-name" value="" class="textbox" size="30" maxlength="200" /></div>
<div class='form-label'>Email (required)</div>
<div class='form-field'><input type="text" name="you-email" value="" class="textbox" size="30" maxlength="200" /></div>
...
</div>
To this:
<div class='form-container'>
...
<div class='form-element-wrapper'>
<div class='form-label'>Name (required)</div>
<div class='form-field'><input type="text" name="you-name" value="" class="textbox" size="30" maxlength="200" /></div>
</div>
<div class='form-element-wrapper'>
<div class='form-label'>Email (required)</div>
<div class='form-field'><input type="text" name="you-email" value="" class="textbox" size="30" maxlength="200" /></div>
</div>
...
</div>
With a jQuery statement like this:
<script type='text/javascript'>
$(".form-container .form-label").each(function(index) {
$(this).next(".form-field").andSelf().wrapAll("<div class='form-element-wrapper' />")
});
</script>
Pop the above tag in some IE7 conditional comments and enjoy.
@reg3x
Copy link

reg3x commented May 30, 2015

Thanks!!

@Screen13
Copy link

Screen13 commented May 9, 2018

Elegant solution. Thanks!

Copy link

ghost commented Jul 26, 2018

Magnifique (y)

@syhien85
Copy link

syhien85 commented Apr 29, 2020

Thanks!
Note: This API (.andSelf()) has been removed in jQuery 3.0; use .addBack() instead, which should work identically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment