title: How to normalize HTML in JavaScript or jQuery?
body: <p>Tags can have multiple attributes. The order in which attributes appear in the code does not matter. For example:</p>
  
  <pre><code>&lt;a href="#" title="#"&gt;
  &lt;a title="#" href="#"&gt;
  </code></pre>
  
  <p>How can I "normalize" the HTML in Javascript, so the order of the attributes is always the same? I don't care which order is chosen, as long as it is always the same. </p>
  
  <p><strong>UPDATE</strong>: my original goal was to make it easier to diff (in JavaScript)  2 HTML pages with slight differences. Because users could use different software to edit the code, the order of the attributes could change. This make the diff too verbose.</p>
  
  <p><strong>ANSWER</strong>: Well, first thanks for all the answers. And YES, it is possible. Here is how I've managed to do it. This is a proof of concept, it can certainly be optimized:</p>
  
  <pre><code>function sort_attributes(a, b) {
    if( a.name == b.name) {
      return 0;
    }
  
    return (a.name &lt; b.name) ? -1 : 1;
  }
  
  $("#original").find('*').each(function() {
    if (this.attributes.length &gt; 1) {
      var attributes = this.attributes;
      var list = [];
  
      for(var i =0; i &lt; attributes.length; i++) {
        list.push(attributes[i]);
      }
  
      list.sort(sort_attributes);
  
      for(var i = 0; i &lt; list.length; i++) {
        this.removeAttribute(list[i].name, list[i].value);
      }
  
      for(var i = 0; i &lt; list.length; i++) {
        this.setAttribute(list[i].name, list[i].value);
      }
    }
  });
  </code></pre>
  
  <p>Same thing for the second element of the diff, <code>$('#different')</code>. Now <code>$('#original').html()</code> and <code>$('#different').html()</code> show HTML code with attributes in the same order.</p>