Created
December 19, 2010 17:17
-
-
Save BigglesZX/747490 to your computer and use it in GitHub Desktop.
Wrap two adjacent elements in a containing div using jQuery
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Elegant solution. Thanks!
Magnifique (y)
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
Thanks!!