neil neil - 5 months ago 10
HTML Question

JavaScript: splitting an HTML list in half

I have a 26-item list with one for each letter of the alphabet

<ul>
<li id="a">A</li>
...
<li id="m">M</li>
<li id="n">N</li>
...
<li id="z">Z</li>
</ul>


How could I use JavaScript to terminate the list after 'M' (i.e.
</ul>
, add an
<h2>
element and start another list, beginning with 'N'?

So:

<ul>
...
<li id="m">M</li>
</ul>
<h2>Part 2</h2>
<ul>
<li id="n">N</li>
...
</ul>


I can insert the
h2
element fine with
.createElement
and
.insertBefore
, but I can't get the closing and opening list tags either side of it. I've tried
innerHTML
,
outerHTML
,
insertBefore
...

Answer

You can get the ul, clone it, insert the clone, and append the childnodes of the ul after the 13th child element to the clone:

var ul = document.querySelector('ul'),
    newUl = ul.cloneNode(false),
    last = ul.children[12];
ul.parentNode.insertBefore(newUl, ul.nextSibling);
ul.parentNode.insertBefore(document.createElement('h2'), newUl)
  .appendChild(document.createTextNode('Part 2'));
while(last.nextSibling) newUl.appendChild(last.nextSibling);

var ul = document.querySelector('ul'),
    newUl = ul.cloneNode(false),
    last = ul.children[12];
ul.parentNode.insertBefore(newUl, ul.nextSibling);
ul.parentNode.insertBefore(document.createElement('h2'), newUl).appendChild(document.createTextNode('Part 2'));
while(last.nextSibling) newUl.appendChild(last.nextSibling);
<ul>
  <li id="a">A</li>
  <li id="b">B</li>
  <li id="c">C</li>
  <li id="d">D</li>
  <li id="e">E</li>
  <li id="f">F</li>
  <li id="g">G</li>
  <li id="h">H</li>
  <li id="i">I</li>
  <li id="j">J</li>
  <li id="k">K</li>
  <li id="l">L</li>
  <li id="m">M</li>
  <li id="n">N</li>
  <li id="o">O</li>
  <li id="p">P</li>
  <li id="q">Q</li>
  <li id="r">R</li>
  <li id="s">S</li>
  <li id="t">T</li>
  <li id="u">U</li>
  <li id="v">V</li>
  <li id="w">W</li>
  <li id="x">X</li>
  <li id="y">Y</li>
  <li id="z">Z</li>
</ul>