Using .after() to add html closing and open tags

You can’t think about DOM modification as if you were editing the original HTML file. Once the browser has parsed the HTML file, to all intents and purposes it no longer exists. The only thing that matters is the DOM representation.

With that in mind, let’s have a look at the bit of code you’ve posted…

.after('</ul><ul>')

You’re imagining this editing the HTML present and adding in a closing tag and an opening tag. It doesn’t. It builds a document fragment from that code and then adds it as a sibling of the element in the original selection. Since </ul> isn’t a valid beginning to a string of HTML, it is dropped. All you have left is <ul>, which is parsed as an element in its entirety (imagine an HTML document that went <div><ul></div> and you’ll get the idea). So an empty ul element is inserted into the list as a sibling of the element you’ve selected: it’s represented as <ul></ul> as this is the way to serialise a ul element to HTML.

To do what you want to do, you’ll need to use a different approach, one that recognises what the DOM is.

$('.container ul').each(function(){
    var total = $(this).children().length;
    var half = Math.ceil(total / 2) - 1;
    $(this).children(':gt('+half+')').detach().wrapAll('<ul></ul>').parent().insertAfter(this);
});

This says “get the children after halfway (:gt), detach them from the current ul, wrap them in a new ul, select that ul with parent and insert it after the current ul (this).”


Working jsFiddle

Leave a Comment