I need to replace the first letter in the div content and wrap it with a <span>
tag.
Here is my html:
<div class="first_ltr">
<p>This is a Test </p>
</div>
I want to replace the html in the form of:
<div class="first_ltr">
<p><span>T</span>his is a Test </p>
</div>
I tried:
$(".first_ltr").each(function () {
var currentText = $(this).html();
$(this).text(currentText.replace("0","<span></span>"));
});
Can any one help? Thanks in advance for help.
You can pass to .html callback, and add any tag to text, like so
$('.first_ltr p').html(function (index, html) {
return '<span>' + html.slice(0, 1) + '</span>' + html.slice(1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="first_ltr">
<p>This is a Test </p>
</div>
html.slice(0, 1)
- returns first letter in string
html.slice(1)
- returns string without first letter
Update I've written small plugin, you can try it
$.fn.wrapText = function (tag, position) {
var $contaiter = $('<div />');
this.html(function (index, html) {
var start = position;
end = position + 1;
if (position > html.length) {
position = 0;
}
$contaiter.html($('<' + tag + '/>').html(html.slice(start, end)));
return [html.slice(0, start), $contaiter.html(), html.slice(end)].join('');
});
};
$('.first_ltr p').wrapText('span', 0);
$('.last_ltr p').wrapText('div', 13);
Example
Not the shortest solution, but it works with every text:
var $span = $('<span />');
$(".first_ltr > p").each(function(){
var firstLetter = $(this).text().slice(0,1); //find first letter
var text = $(this).text().slice(1); //find rest of the text
$span.text(firstLetter); //wrap first letter in span-tag
$(this).text(text); //override old text
$(this).prepend($span); //prepend first letter
});
Demo
Something like this should work for you.
var text = $('.first_ltr p').text();
var split = text.split('');
var firstLetter = split[0];
var rest = split.splice(1,split.length)
$('.first_ltr p').html('<span>' + firstLetter +'</span>' + rest.join(''));
https://jsfiddle.net/d1pf6cjy/1/
Here is a posible solution:
$(document).ready(function(){
var myText = $('.first_ltr > p').text();
var start = '<span>' + myText.slice(0,1) + '</span>';
var end = myText.slice(1, myText.length);
$('.first_ltr > p').html(start + end);
});
Demo: http://jsfiddle.net/r2zp2vqm/1/
Hope it's helps!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With