<p style="width:60px"> I am some random text. I am Some text.blabla</p>
The rendered HTML result of above might be,
I am some ra
ndom text. I
am Some text
.blabla
I would like to split the above paragraph into separate paragraphs row by row. So what the expected result is like,
<p style="width:60px">I am some ra</p>
<p style="width:60px">ndom text. I</p>
<p style="width:60px">am Some text</p>
<p style="width:60px">.blabla</p>
Is it possible to implement it in Javascript?
P.S. Why do I have to split it? Because I would like to get my own pagination system for a long HTML, where all the paragraphs and splited paragraphs within a height range would be put in to a same <div class="page"></div>
. Finally, the whole HTML would be organized as
<div id="page1" class="page">
<p> complete content </p>
<p> upper part of XXX </p>
</div>
<div id="page2" class="page">
<p> bottom part of XXX </p>
<p>...</p><p>...</p>
</div>
Well, assume that your text is in a <p id='wholeText'>
:
var element = document.getElementById("wholeText");
var wholeText = element.innerHTML;
var splitText = wholeText.split("\r\n");
var newHtml = null;
for(var i = 0; i < splitText.length; i++)
{
newHtml += "<p class='each-line'>"+splitText[i]+'</p>';
}
Then you can use newHtml
to write in a DOM element. For instance, if you like to add it to a the same <p>
which you got text from, you do:
element.innerHTML = newHtml; // remember element refers to the <p> with the ID of wholeText
Also put all of the above codes into a function and call the function after the windows has been fully loaded.
window.addEventListener("load", function(){
// put the code here
}, false);
If your line does not contain break characters
, then please refer to this plugin :
http://jsfiddle.net/nathan/qkmse/
The above link is suggested in this SO's question:
detecting line-breaks with jQuery?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With