0

My problem is to split the Dom element using jquery.

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

And I want to Split the above DOM Like this.

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

Please, anybody give me some advice.

2
  • But </split> is not a Valid HTML Tag. Commented Dec 6, 2017 at 9:10
  • Sorry,sorry .... Commented Dec 6, 2017 at 9:10

1 Answer 1

1

One way to do it would be:

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

Demo:

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. If there are no classes (i guess that could be the case), you will have to use different selectors, to target spans (inside container?), with eq(), maybe, but, basically, this simple logic should work...

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.