Giorgi Khatchapuridze
Giorgi Khatchapuridze

Reputation: 71

Wrap words in <span> and ignore <strong> tag

I use this jQuery function to wrap words with <span> in each p element:

$("p").each(function(){
    var text = $(this).text().split(' ');
    for(var i = 0, len = text.length; i < len; i++ ) {
        text[i] = '<span class="outline">' + text[i] + '</span>';
    }
    $(this).html(text.join(' '));
});
span{
  color: blue;
}
strong{
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>We invest with <strong>capital,</strong></p>
<p><strong>know-how, experience</strong></p>
<p><strong>and ambition.</strong></p>

However it removes <strong> from DOM.

I need <strong> tag to stay in DOM even if <span> tag will be generated inside or outside of <strong>

Upvotes: 2

Views: 585

Answers (2)

Barno Chakraborty
Barno Chakraborty

Reputation: 69

Just change the .text to .html and check if it includes any strong element. like this :

$("p").each(function() {
  var text = $(this).html().split(' ');
  for (var i = 0, len = text.length; i < len; i++) {
    if (text[i].includes('<strong>') && !text[i].includes('</strong>')) {
      text[i] = '<span class="outline">' + text[i];
    } else if (!text[i].includes('<strong>') && text[i].includes('</strong>')) {
      text[i] = text[i] + '</span>';
    } else {
      text[i] = '<span class="outline">' + text[i] + '</span>';
    }
  }
  $(this).html(text.join(' '));

});
span {
  color: blue;
}

strong {
  color: red;
}

.outline {
  border: 1px dotted grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>We invest with strong <strong>capital,</strong></p>
<p><strong>know-how, experience</strong></p>
<p><strong>and ambition.</strong></p>

Upvotes: 1

mplungjan
mplungjan

Reputation: 178350

Try using DOM nodes

$("p").html(function() {
  [...this.childNodes].forEach(node => {
    const span = document.createElement("span");
    span.classList.add("outline");
    console.log(node.nodeType,node.innerHTML || node.textContent)
    if (node.nodeType === 3) {
      span.textContent = node.textContent;
    } else {
      span.innerHTML = node.outerHTML
    }
    node.parentNode.replaceChild(span, node)
  })
});
span {
  color: blue;
}

strong {
  color: red;
}

.outline { border: 1px dotted grey; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>We invest with <strong>capital,</strong></p>
<p><strong>know-how, experience</strong></p>
<p><strong>and ambition.</strong></p>

Upvotes: 2

Related Questions