parseHTML.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. define( [
  2. "../core",
  3. "../var/document",
  4. "./var/rsingleTag",
  5. "../manipulation/buildFragment",
  6. // This is the only module that needs core/support
  7. "./support"
  8. ], function( jQuery, document, rsingleTag, buildFragment, support ) {
  9. "use strict";
  10. // Argument "data" should be string of html
  11. // context (optional): If specified, the fragment will be created in this context,
  12. // defaults to document
  13. // keepScripts (optional): If true, will include scripts passed in the html string
  14. jQuery.parseHTML = function( data, context, keepScripts ) {
  15. if ( typeof data !== "string" ) {
  16. return [];
  17. }
  18. if ( typeof context === "boolean" ) {
  19. keepScripts = context;
  20. context = false;
  21. }
  22. var base, parsed, scripts;
  23. if ( !context ) {
  24. // Stop scripts or inline event handlers from being executed immediately
  25. // by using document.implementation
  26. if ( support.createHTMLDocument ) {
  27. context = document.implementation.createHTMLDocument( "" );
  28. // Set the base href for the created document
  29. // so any parsed elements with URLs
  30. // are based on the document's URL (gh-2965)
  31. base = context.createElement( "base" );
  32. base.href = document.location.href;
  33. context.head.appendChild( base );
  34. } else {
  35. context = document;
  36. }
  37. }
  38. parsed = rsingleTag.exec( data );
  39. scripts = !keepScripts && [];
  40. // Single tag
  41. if ( parsed ) {
  42. return [ context.createElement( parsed[ 1 ] ) ];
  43. }
  44. parsed = buildFragment( [ data ], context, scripts );
  45. if ( scripts && scripts.length ) {
  46. jQuery( scripts ).remove();
  47. }
  48. return jQuery.merge( [], parsed.childNodes );
  49. };
  50. return jQuery.parseHTML;
  51. } );