jQuery:使用jQuery拆分DOM节点

时间:2017-12-06 09:08:35

标签: javascript 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>

拜托,请有人给我一些建议。

1 个答案:

答案 0 :(得分:1)

一种方法是:

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

演示:

&#13;
&#13;
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);
&#13;
<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>
&#13;
&#13;
&#13;

P.S。如果没有类(我猜可能是这种情况),你将不得不使用不同的选择器,目标跨度(内部容器?),使用eq(),但是,基本上,这个简单的逻辑应该工作..