title: Setting baseUrl for img tag in HTML fragment
body: <p>I have a page hosted on <code>domain1</code> from which I retrieve, with an ajax call, an HTML fragment which include some  tags. These tags have a relative <code>src</code> URL and I want to set, for these tag only, a base URL pointing to another domain, say <code>domain2</code>.</p>
  
  <p>Here's an example: I have a String <code>HTMLData</code> with the following value:</p>
  
  <pre><code>'&lt;p&gt; Foo &lt;/p&gt; \
  &lt;img alt = "Image 1" src = "/relativepath/To/Image1"&gt; \
  &lt;div class = "someDiv"&gt; \
      &lt;img alt = "Image 2" src = "/relativepath/To/Image2"&gt; \
  &lt;/div&gt;'
  </code></pre>
  
  <p>I want to add to my page something like:</p>
  
  <pre><code>'&lt;p&gt; Foo &lt;/p&gt; \
  &lt;img alt = "Image 1" src = "http://domain2/relativepath/To/Image1"&gt; \
  &lt;div class = "someDiv"&gt; \
      &lt;img alt = "Image 2" src = "http://domain2/relativepath/To/Image2"&gt; \
  &lt;/div&gt;'
  </code></pre>
  
  <p>Of course, I have no idea of the exact structure of the fragment, and I will probably want to extend it to other embedded object tags.</p>
  
  <p>Here is what I have written so far:</p>
  
  <pre><code>function setBaseURLandConstructDiv (HTMLData) {
      var container = document.createElement("div");
      container.innerHTML = HTMLData;
      var images = container.getElementsByTagName("img");
      for (var image = 0;image&lt;images.length;image++) {
          if (images[image].src) {
              images[image].src = 'http://domain2'+ images[image].getAttribute('src');
          }
      }
      return container.innerHTML;
  }
  </code></pre>
  
  <p>It works, but it doesn't seems right to me. In particular, at the line <code>container.innerHTML = HTMLData</code>, the browser make an unnecessary request to <code>http://domain1/relativepath/To/Image1</code>, before making the (correct) call to <code>http://domain2/relativepath/To/Image1</code> at the line  <code>images[image].src = 'http://domain2'+ images[image].getAttribute('src');</code></p>
  
  <p>So is there another method to modify the <code>src</code> attributes? (Or to locally set a base Url)</p>