3

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. 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:

// 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. I can't achieve to use jQuery on my cloned HTML code.

Any idea about how to do this?

Community
  • 1
  • 1
nikoskip
  • 1,860
  • 1
  • 21
  • 38

2 Answers2

5

The DOM is not a string of HTML. With jQuery, you do DOM manipulation, not string manipulation.

What you're doing is

  • cloning the document (unnecessary because you convert it to HTML anyway),

  • appending that cloned document to a new div for some reason

  • converting the content of that div to an HTML string

  • converting that HTML back to DOM nodes $(html) (so we're back to the first point above)

  • finding and removing an element in those nodes

  • presumably posting the html variable to the server.

Unfortunately, the html string has not changed because you manipulated DOM nodes, not the string.


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()

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

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

var html = result.html();
cookie monster
  • 10,671
  • 4
  • 31
  • 45
0

Maybe like this?

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