jQuery:使用jQuery拆分DOM节点



我的问题是使用jQuery分开DOM元素。

<span class="start">
  <span class="second">
   new text <span class='split'>is written</span> in this place.
 </span>
</span>

我想这样拆分上述dom。

<span class="start"><span class="second">new text</span></span>
<span class="start"><span class="second">is written</span></span>
<span class="start"><span class="second">in this place.</span></span>

请给我一些建议。

一种方法是:

last_text=$('.split')[0].nextSibling; //get textNode after split span
prev_text=$('.split')[0].previousSibling; //get text Node before split span
current=$('.split').text(); //get split span text
$('.second').html(' '); //clear current html

cloned1=$('.start').clone(); // clone el
cloned1.insertAfter($('.start'));
cloned2=$('.start').first().clone(); //clone one more
cloned2.insertAfter($('.start').last());
//set text for elements
$('.start .second').eq(0).html(prev_text);
$('.start .second').eq(1).html(current);
$('.start .second').eq(2).html(last_text);

演示:

last_text=$('.split')[0].nextSibling; //get textNode after split span
prev_text=$('.split')[0].previousSibling; //get text Node before split span
current=$('.split').text(); //get split span text
$('.second').html(' '); //clear current html
cloned1=$('.start').clone(); // clone el
cloned1.insertAfter($('.start'));
cloned2=$('.start').first().clone(); //clone one more
cloned2.insertAfter($('.start').last());
//set text for elements
$('.start .second').eq(0).html(prev_text);
$('.start .second').eq(1).html(current);
$('.start .second').eq(2).html(last_text);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="start">
  <span class="second">
   new text <span class='split'>is written</span> in this place.
 </span>
</span>

P.S。如果没有类(我想可能是这样),则您必须使用不同的选择器来定位跨度(内部容器?),也许是EQ(),但是,基本上,这种简单的逻辑应该起作用。。

最新更新