You walked along the correct lines, only there was no convenient way (*) to wrap a number of children, and not just one by one. You must do it yourself, for example:
// Take a range of children in a parent element and wrap them in a new element. // function wrapChildren(tagname, parent, child0, child1) { var wrapper= document.createElement(tagname); for (var i= child1-child0; i-->0;) wrapper.appendChild(parent.childNodes[child0]); parent.insertBefore(wrapper, parent.childNodes[child0]); } // Find `<br>`s and wrap the stretches between them. // var container= document.getElementById('container'); var lastbr= container.childNodes.length; for (var i= lastbr; i-->0;) { var child= container.childNodes[i]; if (child.nodeType===1 && child.tagName.toLowerCase()==='br') { wrapChildren('p', container, i+1, lastbr); container.removeChild(child); lastbr= i; } } wrapChildren('p', container, 0, lastbr);
(*: jQuery or otherwise. Well, there are surroundContents in the DOM Range, but the support is poor.)
source share