wrap.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. jQuery.fn.extend({
  2. wrapAll: function( html ) {
  3. var wrap;
  4. if ( jQuery.isFunction( html ) ) {
  5. return this.each(function( i ) {
  6. jQuery( this ).wrapAll( html.call(this, i) );
  7. });
  8. }
  9. if ( this[ 0 ] ) {
  10. // The elements to wrap the target around
  11. wrap = jQuery( html, this[ 0 ].ownerDocument ).eq( 0 ).clone( true );
  12. if ( this[ 0 ].parentNode ) {
  13. wrap.insertBefore( this[ 0 ] );
  14. }
  15. wrap.map(function() {
  16. var elem = this;
  17. while ( elem.firstElementChild ) {
  18. elem = elem.firstElementChild;
  19. }
  20. return elem;
  21. }).append( this );
  22. }
  23. return this;
  24. },
  25. wrapInner: function( html ) {
  26. if ( jQuery.isFunction( html ) ) {
  27. return this.each(function( i ) {
  28. jQuery( this ).wrapInner( html.call(this, i) );
  29. });
  30. }
  31. return this.each(function() {
  32. var self = jQuery( this ),
  33. contents = self.contents();
  34. if ( contents.length ) {
  35. contents.wrapAll( html );
  36. } else {
  37. self.append( html );
  38. }
  39. });
  40. },
  41. wrap: function( html ) {
  42. var isFunction = jQuery.isFunction( html );
  43. return this.each(function( i ) {
  44. jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
  45. });
  46. },
  47. unwrap: function() {
  48. return this.parent().each(function() {
  49. if ( !jQuery.nodeName( this, "body" ) ) {
  50. jQuery( this ).replaceWith( this.childNodes );
  51. }
  52. }).end();
  53. }
  54. });