使用jQuery编辑outerHTML的结果

时间:2014-08-22 20:29:31

标签: javascript jquery html

我试图阅读整个页面的HTML(包括doctype),然后删除页面的一些部分,以便通过AJAX将其作为字符串传递。

到目前为止我所拥有的是:

var page = doctype + document.documentElement.outerHTML;

这给了我想要的内容,但是当我尝试使用jQuery的.remove()函数时,我得到了undefined is not a function

page.remove(".my-class");

我认为我对变量类型做错了吗?如何获取整页源代码,以便我仍然可以使用jQuery操作它?

3 个答案:

答案 0 :(得分:0)

您需要将html放入jQuery对象中才能操作它。完成后,您可以使用jQuery的find method then remove method删除与.my-class匹配的元素:

var $page = $(doctype + document.documentElement.outerHTML);
$page.find(".my-class").remove();

之后,您可以通过执行以下操作获取生成的HTML:

var htmlToSendViaAjax = $page[0].outerHTML;

答案 1 :(得分:0)

如果你想用jQuery操作HTML,你必须调用jQuery构造函数:

var page = $(doctype + document.documentElement.outerHTML);
page.remove(".my-class");

答案 2 :(得分:-1)

您的问题是page不是jQuery对象,因此没有像.remove()这样的方法。

如果你想使用jQuery的outerHTML,你需要做一个jQuery选择:

$("#selector");
$(document); // for the entire document

然后你可以使用找到here的解决方案来获取选择中第一个元素的outerHTML(你可以使用foreach循环来执行大量的元素:

var $selection = $("#selector")
$selection[0].outerHTML;