title: JS/jQuery - rearranging an HTML table element
body: <p>I have a table on my site and it is too long across for mobile so am trying to invert it so that it is like:</p>
  
  <pre><code>1 a
  2 b
  3 c
  4 d
  </code></pre>
  
  <p>instead of like:</p>
  
  <pre><code>1 2 3 4
  a b c d
  </code></pre>
  
  <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
  <div class="snippet-code">
  <pre class="snippet-code-js lang-js prettyprint-override"><code>$("#table").each(function() {
    var $this = $(this);
    var newrows = [];
    $this.find("tr").each(function(){
      var i = 0;
      $(this).find("td").each(function(){
        i++;
        if(newrows[i] === undefined) { newrows[i] = $("&lt;tr&gt;&lt;/tr&gt;"); }
        newrows[i].append($(this));
      });
    });
    $this.find("tr").remove();
    $.each(newrows, function(){
      $this.append(this);
    });
  });</code></pre>
  <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"&gt;&lt;/script&gt;
  &lt;table id="table"&gt;
  &lt;tr&gt;
    &lt;td&gt;1&lt;/td&gt;
    &lt;td&gt;2&lt;/td&gt;
    &lt;td&gt;3&lt;/td&gt;
    &lt;td&gt;4&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;a&lt;/td&gt;
    &lt;td&gt;b&lt;/td&gt;
    &lt;td&gt;c&lt;/td&gt;
    &lt;td&gt;d&lt;/td&gt;
  &lt;/tr&gt;
  &lt;/table&gt;</code></pre>
  </div>
  </div>
  </p>
  
  <p>I found this function and it works fine in some cases but not all (of course, typically, it works fine in this snippet) but on other devices I get an error:</p>
  
  <pre><code>Uncaught TypeError: Cannot read property 'ownerDocument' of undefined
      at Function.oe.contains (jquery.js:2)
      at xe (jquery.js:2)
      at Re (jquery.js:2)
      at w.fn.init.append (jquery.js:2)
      at script.js:35
      at Function.each (jquery.js:2)
      at HTMLTableElement.&lt;anonymous&gt; (script.js:34)
      at Function.each (jquery.js:2)
      at w.fn.init.each (jquery.js:2)
      at HTMLDocument.&lt;anonymous&gt; (script.js:22)
  </code></pre>
  
  <p>Lines 34+35 from this error refers to:</p>
  
  <pre><code>$.each(newrows, function(){
    $this.append(this);
  </code></pre>