<script type="text/javascript"> jQuery.fn.nextUntil = function(expr, includes){ var match = []; includeFirst = includes.first ? true : false; includeLast = includes.last ? true : false; // We need to figure out which elements to push onto the array this.each(function(){ // Traverse through the sibling nodes if (includeFirst) match.push(this); for (var i = this.nextSibling; i; i = i.nextSibling) { // Make sure that we're only dealing with elements if (i.nodeType != 1) continue;
// Add it on to the stack if include is set if (includeLast) { match.push(i); } // If we find a match then we need to stop if (jQuery.filter(expr, [i]).length) break; // Add it on to the stack if include is not set if (!includeLast) { match.push(i); } } }); return this.pushStack(match, arguments); } $(document).ready(function(){ $('label').each(function(){ $(this).nextUntil('label', {first: true, last: false}).wrapAll('<div class="field">'); }); }); </script> </head> <body> <form> <label for="name"> Name </label> <input id="name" value="Kristian"> <label for="age"> Age </label> <input id="age" value="32"> </form> </body>