I have a manipulated HTML text like this:
Lorem ipsum <a href="#">dolor</a> sit amet
<div>Consectetur adipisicing elit, sed do </div> eiusmod tempor
incididunt ut labore et dolore magna aliqua.
I need to convert these lines into this:
<p>Lorem ipsum <a href="#">dolor</a> sit amet</p>
<div>Consectetur adipisicing elit, sed do </div>
<p>eiusmod tempor</p>
<p>incididunt ut labore et dolore magna aliqua</p>
How to convert? Any ideas? Thank you!
This is a little lengthy, so please read carefully. I have annotated the important parts to give a general idea as to the flow of the function.
This function will do as you have specified in your example.
Paragraphifyiterates through the children nodes of theparentargument, skipping<div>and<p>elements, as those need not be formatted. It creates a paragraph node and moves the parent's nodes in, one at a time, until it encounters a newline character within a text node, at which time it splits the text node appropriately.This is processed until the parent element is empty. The workspace elements are then transferred back into parent. This was done to make processing much simpler, as manipulating a collection that you are actively iterating can be messy.
I should warn that this does not descend further than the parent's immediate children, but if you have this need, please let me know. To put that basically, this function would not perform this translation:
... into ...
Even then, this should be a good example of the base functionality required for line processing in HTML with basic Javascript.
jsFiddle Demonstration