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?

4
  • $('<div>') ... do you mean $('div') ? Commented Feb 21, 2014 at 16:24
  • 1
    @andymccullough, he is creating the div as a container for the html to be put in. not pulling all of the divs from the html and putting the html in them. Commented Feb 21, 2014 at 16:26
  • That's right @smerny ;) Commented Feb 21, 2014 at 16:29
  • ah cool, didnt know that is what that done, learn something new everyday Commented Feb 21, 2014 at 16:29

2 Answers 2

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();
Sign up to request clarification or add additional context in comments.

1 Comment

You are right, you have clarified me the concept. I was very close! hahaha. Thanks a lot.
0

Maybe like this?

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

1 Comment

Seems like you're guessing. What is being posted to the server?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.