将dom元素中的所有文本拆分为<span> </span>

时间:2012-09-25 21:07:23

标签: javascript jquery html

我想将html DOM节点内的所有元素拆分为带有id的跨度,例如:

假设我有元素:

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

,结果应为:

<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>

感谢您的帮助

如果有嵌套图像,它也可以工作:

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

结果:

<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>

2 个答案:

答案 0 :(得分:7)

jsBin demo

要将每个单词包装成这样的内容应该有所帮助:

var c = 0;                                // create a counter
$('div > *').each(function(){
    var text = $(this).html().split(' '), // split your text strings
        len = text.length,                // get lenght of splitted parts
        result = [];                      // create array
    for( i=0; i<len; i++ ) {              // looping 'len' times....
        result[i] = '<span id="'+( ++c )+'">' + text[i] + '</span>';  // populate array
    }
    $(this).html(result.join(' '));       // apply edits
});   

答案 1 :(得分:0)

var str = $('.test').text();
var result = "";
str = str.split(" ");
$.each(str,function() {
   result += '<span>' + this + '</span>';
});
$('.test').html($(result));