0

I want to wrap the sentences individually with new tag within <p>. How can I do that using JQuery? I know I can do this with $(p).contents().eq(2).wrap('<span/>') and $(p).contents().eq(4).wrap('<span/>'), but this is hardcoded. The number of sentences in the paragraph I have are dynamic.

<!-- How do I change this -->
<p>
  <span>1</span>
  This is the 1st sentence.
  <span>2</span>
  This is the 2nd sentence.
</p>

<!-- to become this? -->
<p>
  <span>1</span>
  <span>This is the 1st sentence.</span>
  <span>2</span>
  <span>This is the 2nd sentence.</span>
</p>
M Amos
  • 13
  • 2

2 Answers2

1

You can spit the paragraphs child elements by line break character and then loop through it check if the span wrapper exists.

Check below sample.

var p = document.querySelector("p");

var pChild = p.innerHTML.split('\n');

var pChildWrapped = pChild.map(function(e){
    return e.indexOf('<span>') !== -1 ? e : `<span>${e.trim()}</span>`;
});

console.log(pChildWrapped.join('\n'));

// You can change paragraph content as below
// p.innerHTML = pChildWrapped.join('\n');
<p>
  <span>1</span>
  This is the 1st sentence.
  <span>2</span>
  This is the 2nd sentence.
</p>
Rohit Utekar
  • 828
  • 5
  • 10
  • Sorry Rohit, My paragraph don't have line breaks. There all are in 1 line. I line break them just for easy read. Thanks anyway. :) – M Amos Oct 01 '20 at 03:42
0

Use contents() and filter the non empty textNodes (nodeType ===3) and wrap() those

$('p').contents().filter(function(){
   return this.nodeType === 3 && !!this.textContent.trim();   
}).wrap('<span style="color:red">')
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
  <span>1</span>
  This is the 1st sentence.
  <span>2</span>
  This is the 2nd sentence.
</p>
charlietfl
  • 170,828
  • 13
  • 121
  • 150