wrap.js 1.4 KB

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