简体   繁体   English

克隆HTML并使用jQuery删除一些节点

[英]Clone HTML and remove some nodes using jQuery

I'm developing a little tool for live editing using Chrome DevTools, and I have a little button "Save" which grabs the HTML and sends it to server to update the static file (.html) using Ajax. 我正在使用Chrome DevTools开发一个用于实时编辑的小工具,我有一个小按钮“保存”,它抓取HTML并将其发送到服务器以使用Ajax更新静态文件(.html)。 Very simple indeed. 确实很简单。

My problem is that I need to filter the HTML code before sending it to the server, I need to remove some nodes and I'm trying to achive this using jQuery, something like this: 我的问题是我需要在将HTML代码发送到服务器之前对其进行过滤,我需要删除一些节点,并且我正在尝试使用jQuery实现这一点,如下所示:

// I grab all the HTML code
var html = $('<div>').append($('html').clone()).html();
// Now I need to remove some nodes using jQuery
$(html).find('#some-node').remove();
// Send the filtered HTML to server
$.post('url/to/server/blahblahblah');

I already tried this Using jQuery to search a string of HTML with no success. 我已经尝试过使用jQuery搜索HTML字符串但没有成功。 I can't achieve to use jQuery on my cloned HTML code. 我无法在克隆的HTML代码上使用jQuery。

Any idea about how to do this? 有关如何做到这一点的任何想法?

The DOM is not a string of HTML. DOM不是HTML字符串。 With jQuery, you do DOM manipulation, not string manipulation. 使用jQuery,您可以执行DOM操作,而不是字符串操作。

What you're doing is 你在做什么

  • cloning the document (unnecessary because you convert it to HTML anyway) , 克隆文档(不必要,因为你无论如何都将它转换为HTML)

  • appending that cloned document to a new div for some reason 由于某种原因将克隆文档附加到新div

  • converting the content of that div to an HTML string 将该div的内容转换为HTML字符串

  • converting that HTML back to DOM nodes $(html) (so we're back to the first point above) 将该HTML转换回DOM节点$(html) (所以我们回到上面的第一点)

  • finding and removing an element in those nodes 查找和删除这些节点中的元素

  • presumably posting the html variable to the server. 可能是html变量发布到服务器。

Unfortunately, the html string has not changed because you manipulated DOM nodes, not the string. 不幸的是, html字符串没有改变,因为你操纵了DOM节点,而不是字符串。


Hopefully you can see above that you're doing all sorts of conversions that have little to do with what you ultimately want. 希望您可以在上面看到,您正在进行各种与您最终想要的内容无关的转换。

I don't know wny you'd need to do this, but all you need is to do a .clone() , then the .find().remove() , then .html() 我不知道你是否需要这样做,但你需要的只是做一个.clone() ,然后是.find().remove() ,然后是.html()

var result = $("html").clone(false);

result.find("#some-node").remove();

var html = result.html();

Maybe like this? 也许是这样的?

var html = $('html').clone();
html.find('#some-node').remove();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM