将整个HTML页面存储到jQuery Variable中

时间:2017-04-20 17:34:08

标签: javascript jquery html codemirror

我有一个使用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。我没有尝试过任何想法吗?

1 个答案:

答案 0 :(得分:3)

看来你可以做你想做的事。您只需创建一个新文档,可能还需要创建第二个jQuery实例。

您应该看一下:https://stackoverflow.com/a/15496537/1819684和此:https://stackoverflow.com/a/15479402/1819684

&#13;
&#13;
$(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'));
});
&#13;
<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>
&#13;
&#13;
&#13;