Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In JavaScript, how can serializer part of the DOM to XHTML?

I would like to serialize part of the DOM to XHTML (valid XML). Let's assume I have just one element inside <body>, and that this is the element I want to serialize:

<div>
    <hr>
    <img src="/foo.png">
</div>

With this, document.innerHTML gives me almost what I want, except it returns HTML, not XHTML (i.e. the <hr> and <img> won't be properly closed). Since innerHTML doesn't do the trick, how can I serialize part of the DOM to XHTML?

like image 441
avernet Avatar asked Sep 27 '11 23:09

avernet


1 Answers

I am not sure if using another language (on top of the JavaScript engine) is an option. If this is of any help, this would be the XQuery (XQIB) way of doing it:

<script type="application/xquery">
  serialize(b:dom()//div)
</script>

For example, in the following page, the serialized XHTML is written as text on the page instead of the script tag, after the div tag:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>   
    <title>Serializing part of the DOM</title>
    <meta charset="UTF-8"/>
    <script type="text/javascript" src="mxqueryjs/mxqueryjs.nocache.js"></script>
  </head>
  <body>
    <div>
      <hr>
      <img src="/foo.png">
    </div>
    <script type="application/xquery">
      serialize(b:dom()//div)
    </script>
  </body>
</html>

The HTML DOM is mapped to the XQuery data model (a data model on top of XML). b:dom() returns the document node of the page, and //div navigates to all descendant div tags. The serialize function then serializes this to a string.

However, this will work for IE9+ (not 6+) and recent versions of Chrome, Firefox, Safari, Opera.

like image 120
Ghislain Fourny Avatar answered Oct 06 '22 00:10

Ghislain Fourny