Pratik Garg
Pratik Garg

Reputation: 977

Conditionally adding a <br> to text within a <p> tag using jQuery

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

Upvotes: 0

Views: 1316

Answers (3)

Ariel
Ariel

Reputation: 4500

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>
    }
});

Upvotes: 1

jay
jay

Reputation: 10325

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

Upvotes: 2

John Boker
John Boker

Reputation: 83719

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/

Upvotes: 1

Related Questions