split all text inside dom element into <span>

Posted by gruber on Stack Overflow See other posts from Stack Overflow or by gruber
Published on 2012-09-25T21:07:22Z Indexed on 2012/09/25 21:37 UTC
Read the original article Hit count: 296

Filed under:
|
|

I would like to split all elements inside html DOM node into spans with ids, for example:

lets say I have element:

<div>
<h1>Header</h1>
<h2>header2</h2>
<p class="test">this is test p</p>
</div>

and the result should be:

<div>
<h1><span id="1">Header</span></h1>
<h2><span id="2">header2</span></h2>
<p class="test"><span id="3">this</span><span id="4">is</span><span id="5">test</span> <span id="6">p</span></p>
</div>

thanks for any help

it shoul also work if there are nested images for example:

<div>
<h1>Header</h1>
<h2>header2</h2>
<p class="test"><img alt="test alt" />this is test p</p>
</div>

and the result:

<div>
<h1><span id="1">Header</span></h1>
<h2><span id="2">header2</span></h2>
<p class="test"><img alt="test alt" /><span id="3">this</span><span id="4">is</span><span id="5">test</span> <span id="6">p</span></p>
</div>

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about jQuery