dubbs dubbs - 5 months ago 21
jQuery Question

Wrapping lines of text inside <pre> with <span>

I am looking for a jquery solution to dynamically wrap the contents of my

<pre>
code which is written as below, to wrap each line with a
<span>
and
</span>
element so that my CSS styling for line numbers works.

Any ideas on how to do this?

<pre>
This is the first line of pre text.
This is the 2nd line...
This is the 3rd line etc etc you get the ideas...
<pre>


The above needs to be amended by jQuery to become:

<pre>
<span>This is the first line of pre text.</span>
<span>This is the 2nd line...</span>
<span>This is the 3rd line etc etc you get the ideas...</span>
<pre>

Answer

Use html() method with callback in jQuery to iterate and update content, where String#split and Array#join methods van use for generate the content.

$('pre').html(function(i, old) {
  return '<span>' + old.split('\n').join('</span>\n<span>') + '</span>';
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre>
This is the first line of pre text.
This is the 2nd line...
This is the 3rd line etc etc you get the ideas...
</pre>