tags:

views:

61

answers:

3

I have HTML code like this:

<div id="paragraph">
<pre>
<p>First Line in the paragraph , this goes very long and very very long</p>
<p>This line is of normal size
</pre>
</div>

Now, because of the first line, I get a scroll bar in my dialog box. I want to use jQuery and break the text inside the all <p> tag inside the "paragraph" div if it's greater than certain length during body load. So that it becomes something like this:

<div id="paragraph">
<pre>
<p>First Line in the paragraph , this goes very long
<br/>
and very very long</p>
<p>This line is of normal size
</pre>
</div>

Is there a way to do this using jQuery?

Thanks! Pratik

+1  A: 

I'm not sure about doing this with jquery, but using the method here with css you can have the text auto wrap

http://www.longren.org/2006/09/27/wrapping-text-inside-pre-tags/

John Boker
I have tried this , it doesn't works for a dialog box when it size is smaller than the window size.
Pratik
I'd have to see an actual example of this to debug it.
John Boker
+2  A: 

You'll get a scroll bar using <pre> tag because it will not allow your paragraph tag to wrap. Use it without that tag.

jeerose
the html content is coming from a service , so i dont want to remove the pre
Pratik
If you're already getting the HTML via jQuery's AJAX, why not?
S Pangborn
I would be very wary about displaying HTML from an external service (with all the XSS possibilities). If it's generally simple and predictable output like always a couple of lines in a `<p>` I'd prefer to extract the `text()` from the relevant part of the returned value, and format it myself (without the `<pre>` obv).
bobince
@bobince, can loading external HTML potentially execute scripts contained in the HTML itself, out of curiosity?
jeerose
Yes, certainly, depending on how you do it. Setting `innerHTML` to a string including `<script>` won't immediately execute the script, but further DOM manipulation can do (this varies somewhat between browsers). And of course the other ways of injecting script such as `onmouseover` will work just fine.
bobince
That seems like a great reason right there for NOT doing what @Pratik is doing!
jeerose
+1  A: 

You should loop through all <p> elements, get the length of their text, and then apply the line breaks.

$(document).ready(function() {
    $("p").each(function(i, item) {
        if($(item).text().length > 10) $(item).text(breakLongLine($(item).text()));
    });

    function breakLongLine(text) {
        // add </br>
    }
});
Ariel