jQuery.fn.innerWrap = function() { var a, args = arguments; return this.each(function() { if (!a) a = jQuery.clean(args, this.ownerDocument); // Clone the structure that we’re using to wrap var b = a[0].cloneNode(true), c = b; // Find the deepest point in the wrap structure while ( b.firstChild ) b = b.firstChild; // append the child nodes to the wrapper jQuery.each(this.childNodes, function(i, node) { b.appendChild(node); }); jQuery(this) // clear the element .empty() // add the new wrapper with the previous child nodes appended .append(c); }); };
Usage:
The following example would effectively turn <h2>Title</h2> into <h2><span>Title</span></h2>
$(document).ready(function(){ $(‘h2′).innerWrap(‘<span></span>’) });