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

ⅰ亾dé卋堺 提交于 2019-11-27 05:29:56

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

You can't add half tags to the DOM, you can only add complete elements. When you try, the browser does it's best to correct the code, and you end up with <ul></ul> instead of </ul><ul>. (The actual result can differ between browsers, as they have different strategies for correcting incorrect code.)

Instead, add another ul element after the first, and move half of the items to it:

$('.container ul').each(function(){

  var total = $(this).children().length;
  var half = Math.ceil(total / 2) - 1;
  $(this).after('<ul/>').append($(this).children(':gt('+half+')'));

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!