Never been to CodeSnippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world (or not, you can keep them private!)

jQuery.innerWrap (See related posts)

The innerWrap method acts almost identical to the wrap method. The only real difference is that it wraps the contents of the element instead of the actual element. Authored by Brandon Aaron, author of the fantastic jQuery.Dimensions plugin.


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>’)
});



You need to create an account or log in to post comments to this site.