将整个 HTML 页面存储到 jQuery 变量中

Store Entire HTML page into jQuery Variable

我有一个使用 HTML 电子邮件模板的应用程序。我想编写一个脚本来解析电子邮件模板的 HTML 并修改代码。当模板加载到页面上时这很容易,但我想动态地执行这些操作,其中 HTML 只是 <textarea>(或更具体地说是 CodeMirror)的值。

<textarea> (CodeMirror) 的值如下所示:

<!doctype html>
<html>
  <head>...HEAD HTML...</head>
  <body>...BODY HTML...</body>
</html>

我试过:

// This part works great. Stores the HTML as a varaible. 
var template_html = codeMirrorInstance.getValue(); 

// This shows the proper HTML in console as text
console.log(template_html);

// From here I can't access the HTML though
console.log($(template_html).find('body'));

但我不断得到 undefined。我尝试的任何方法都不起作用...有什么想法吗?

看起来你可以做你想做的事。您只需创建一个新文档,并可能创建 jQuery.

的第二个实例

你应该看看这个: and this:

$(function() {
  var doctype = document.implementation.createDocumentType( 'html', '', '');
  var dom = document.implementation.createDocument('', 'html', doctype);
  
  var jq2 = jQuery(dom);
  var txt = $('textarea').val();
  
  console.log(jq2.find('html').html(txt).find('body'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea>
<html>
  <head>...HEAD HTML...</head>
  <body>...BODY HTML...</body>
</html>
</textarea>