JQuery - How to convert html from br to it to html with p in it?

On my page I have html like this:

hi<br>bye<br>sigh<br>hello <em>tie</em><br>lie 

with jquery, how can I convert it to html like this (basically using p instead of br):

 <p>hi</p><p>bye</p><p>sigh</p><p>hello <em>tie</em></p><p>lie</p> 

My first attempt to do this is this code:

 $(container).contents().filter(function() { var val = this.nodeValue; return this.nodeType == TEXT_NODE && $.trim(val).length > 0; }) .wrap('<p></p>') .end() .filter('br') .remove(); 

This worked for the most part, except that hello and <em>tie</em> would not be in the same p element.

Does anyone know how I can do this correctly?

+4
source share
3 answers

simple javascript solution

  var obj = document.getElementById ('container'),
     str = obj.innerHTML,
     ar = str.split ('<br />'),
     result = "";
 for (var i = 0; i <ar.length; i ++)
 {
  result + = '<p>' + ar [i] + '</p>';
 }
 obj.innerHTML = result;

I don't know how to do this with jQuery ...

+1
source

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.)

+1
source
 '<p>'+html.replace(/<br\s?\/?>/gi,'</p><p>')+'</p>' 

never tested. but this is an idea.

0
source

Source: https://habr.com/ru/post/1307737/


All Articles