dragonore dragonore - 5 months ago 8x
HTML Question

Add a span tag inside p after certain amount of characters

Suppose you have this for your HTML:

<div class="contentBox">
<p>I have some content that is good to read</p>

However you would like to add a span tag after a certain amount of characters, lets say 26 characters, which would be right after the word "that". The result would look like this:

<div class="contentBox">
<p>I have some content that<span> is good to read</span></p>

It has to be after a certain amount of characters, because the paragraph will change from time to time.


Set the amount of characters after you want to set the span. Get text of the p element. Substring from start until the amount of chars, add the span, continue with the rest and add the closing span


var after=26;
var html = $(".contentBox p").html();
html = html.substring(0, after) + "<span>" + html.substring(after)+"</span>";
$(".contentBox p").html(html);