Understanding 'parentNode' of undefined error
<p>I'm practicing basic JS skills by setting up little exercises for myself. In this one, I have a list of <code>&lt;a&gt;</code>s inside a div. The aim of the exercise is to wrap each <code>&lt;a&gt;</code> in a div. I'm using <code>replaceChild</code> in this instance. </p>

<p>Oddly (to me at least) the script works for the first three links, but after that throws an error:</p>

<blockquote>
  <p>Uncaught TypeError: Cannot read property 'parentNode' of undefined</p>
</blockquote>

<p>I can't tell why the script partly works. Can anyone see what I'm doing wrong here? Here's the code I'm using:</p>

<pre><code>&lt;!DOCTYPE html&gt;
&lt;html lang="en"&gt;
&lt;head&gt;
&lt;meta charset="utf-8"&gt;

&lt;style media="all"&gt;
div div {padding: 10px; background: #e7e7e7; margin: 5px;}
&lt;/style&gt;

&lt;/head&gt;
&lt;body&gt;

&lt;div&gt;
    &lt;a href=""&gt;link&lt;/a&gt;
    &lt;a href=""&gt;link&lt;/a&gt;
    &lt;a href=""&gt;link&lt;/a&gt;
    &lt;a href=""&gt;link&lt;/a&gt;
    &lt;a href=""&gt;link&lt;/a&gt;
    &lt;a href=""&gt;link&lt;/a&gt;
&lt;/div&gt;

&lt;script&gt;
var links = document.getElementsByTagName("a");
for (var i=0, ii=links.length; i&lt;ii; i++) 
{
    var container = document.createElement("div");
    links[i].parentNode.replaceChild(container, links[i]);
    container.appendChild(links[i]);
}
&lt;/script&gt;

&lt;/body&gt;
&lt;/html&gt;
</code></pre>

<p>and here's an online version: <a href="http://codepen.io/anon/pen/Lpuky" rel="nofollow">http://codepen.io/anon/pen/Lpuky</a></p>

<p>I've tried the few debugging techniques that I know of and read about this error message, but haven't worked out what's wrong here. Seems funny to me that it works for 3 of the 6 links.</p>
