title: jQuery: Parse/Manipulate HTML without executing scripts
body: <p>I'm loading some HTML via Ajax with this format:</p>
  
  <pre><code>&lt;div id="div1"&gt;
    ... some content ...
  &lt;/div&gt;
  &lt;div id="div2"&gt;
    ...some content...
  &lt;/div&gt;
  ... etc.
  </code></pre>
  
  <p>I need to iterate over each div in the response and handle it separately. Having a separate string for the HTML content of each div mapped to the id would satisfy my requirements. However, the divs may contain script tags, which I need to preserve but not execute (they'll execute later when I stick the HTML into the document, so executing during parsing would be bad). My first thought was to do something like this:</p>
  
  <pre><code>// data being the result from $.get
  var clean = data.replace(/&lt;script.*?&lt;/script&gt;/,function() {
      // insert some unique token, save the tag, put it back while I'm processing
  }); 
  
  $('&lt;div/&gt;').html(clean).children().each( /* ... process here ... */);
  </code></pre>
  
  <p>But I worry that some stupid dev is going to come along and put something like this in one of the divs:</p>
  
  <pre><code>&lt;script&gt; var foo = '&lt;/script&gt;'; // ... &lt;/script&gt;
  </code></pre>
  
  <p>Which would screw it all up. Not to mention, the whole thing feels like a hack to begin with. Does anyone know a better way?</p>
  
  <p>EDIT: Here's the solution I've come up with:</p>
  
  <pre><code>var divSplitRegex = /(?:^|&lt;\/div&gt;)\s*&lt;div\s+id="prefix-(.+?)"&gt;/g,
      idReplacement = preDelimeter+'$1'+postDelimeter;
  var r = data.replace(&lt;\/div&gt;\s*$/,'').
      replace(divSplitRegex,idReplacement).split(preDelimeter);
  $.each(r,function() {
      var content;
      if(this) {
          callback.apply(null,this.split(postDelimeter));
      }
  });
  </code></pre>
  
  <p>Where preDelimiter and postDelimeter are just unique strings like "###I'd have to be an idiot to embed this string in my content unescaped because it would break everything###', and callback is a function expecting the div id and the div content. This only works because I know that the divs will have only an id atribute, and the id will have a special prefix. I suppose someone could put a div in their content with an id having the same prefix and it would screw things up too. </p>
  
  <p>So, I still don't love this solution. Anyone have a better one?</p>