0

I need to edit an HTML document using jQuery, but all solutions I have tried are very restrictive.

I am fetching the document from the server, so I get it as a string. In order to parse the document, I need to add it in the DOM.

When I append it to the body, I lose <html>, <head> and <body> tags, which are stripped by the browser (see https://stackoverflow.com/a/3218941/654179).

So I tried using an iframe, which is a bit complex: I have to use contentWindow.document to fill it manually, then a trick with contents().find('*').html() to get the content. Maybe there is a simpler, cleaner way of doing this. But the iframe solution also strips <html>, <head> and <body> tags. See my example: http://jsfiddle.net/gNvYn/7/

There is another trick here: https://stackoverflow.com/a/6751201/654179 but I couldn't use it for writing then reading the document (I need to read it for saving on the server).

So, is there a way to edit (write, then read) an HTML document without losing the structure?

Community
  • 1
  • 1
Clément
  • 602
  • 1
  • 8
  • 14
  • Do you really have to append it to the DOM? Did you try using just $(varContainingHtmlAsString)? – bfavaretto Mar 15 '12 at 18:32
  • Getting the document might actually be less of a problem than writing it. How do you want to do that? Do you have a server side service which accepts text and a file name (for example) and writes the content to that file? – Felix Kling Mar 15 '12 at 18:34
  • editing a html document through jQuery is limited and probably not the best solution. try php – t q Mar 15 '12 at 18:36
  • @bfavaretto: Yes, I tried. See http://jsfiddle.net/anr23/ – Clément Mar 15 '12 at 18:39
  • @FelixKling: This is a Backbone application and the document is a model. So I can fetch it an the save it to the server. But my problem is the way I edit the content before saving it. – Clément Mar 15 '12 at 18:39
  • If browser support is not an issue, you can use the [`DOMParser` with MIME-type `text/html`](http://stackoverflow.com/a/9251106/938089?javascript-domparser-access-innerhtml-and-other-properties). – Rob W Mar 15 '12 at 18:40
  • @Rob: this is actually an issue. – Clément Mar 15 '12 at 19:01

1 Answers1

1

If the things that you need to change are entirely within the body, then there is a workaround. Use javascript's indexOf() and slice() methods to split the string into pre-body (which has <body> as its last characters), post-body (which has </body> as its first characters), and body (everything in the middle). Then insert the body into the DOM, manipulate it, pull it back out again, use the javascript + operator to stick the three back together again, and send back. It's a little kludgy, and it's not exactly what you asked for, but it should get you where you're going.

Ben Barden
  • 2,001
  • 2
  • 20
  • 28