Add A Span Tag Inside P After Certain Amount Of Characters
Suppose you have this for your HTML: However you would like to add a s
I have some content that is good to read
Solution 1:
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
Try:
var after=26;
var html = $(".contentBox p").html();
html = html.substring(0, after) + "<span>" + html.substring(after)+"</span>";
$(".contentBox p").html(html);
Solution 2:
String.prototype.insertTextAtIndices = function (text) {
returnthis.replace(/./g, function (char, index) {
return text[index] ? text[index] + char : char;
});
};
//usagevar range = {
25: "<span style='color:red'>",
40: "</span>"
};
document.getElementsByTagName("p")[0].innerHTML = document.getElementsByTagName("p")[0].innerHTML.insertTextAtIndices(range);
Solution 3:
You can make use of JavaScript's substr
method.
functionaddSpan($elems) {
$elems.each(function() {
var $elem = $(this),
text = $elem.text();
if (text.length <= 25)
return;
var start = text.substr(0, 25), // "I have some content that "
end = text.substr(25, text.length); // "is good to read"
$elem.html(start + '<span>' + end + '</span>');
});
}
addSpan($('.contentBox').find('p'));
span {
color: #f00;
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><divclass="contentBox"><p>I have some content that is good to read</p></div><divclass="contentBox"><p>I have some content that is good to read and this is a much longer string!</p></div>
Solution 4:
Try this : get first part and second part of the string using substring()
and modify text with span
element to put it into html
of p
tag.
Below function will iterate all p
under contentBox
div, but if you are targeting only one div then you can use it without .each()
$(function(){
$('.contentBox p').each(function(){
var text = $(this).text();
var first = text.substring(0,26);
var second = text.substring(26,text.length);
$(this).html(first + '<span>' + second + '</span>');
});
});
Post a Comment for "Add A Span Tag Inside P After Certain Amount Of Characters"