Hammad Munir Hammad Munir - 3 months ago 9
jQuery Question

i want to get first letter of every paragraph from specific div javascript/jquery

i want to get first letter of every paragraph from specific div using java script or jquery and append that letter into same paragraph.

here is my html code:

<div id="about-content" class="aboutus-entry-content">
<p>Maecenas facilisis nec velit Integer lacinia eros vitae risus euismod interdum. Nam ornare cursus nulla, ac pulvinar velit congue eu. Quisque vehicula nulla vel accumsan convallis.</p>
<p>Curabitur iaculis sodales turpis non feugiat. Praesent scelerisque varius mi eu molestie. Etiam vitae mi augue. Nulla fringilla congue scelerisque. Donec eget pretium leo. Aenean nunc est, elementum</p>

<p>Nunc eget ullamcorper nunc. Ut ac elit lacus. Sed placerat vestibulum est. Ut nec pulvinar turpis, quis aliquam libero.</p>

</div>


Example:

<div id="about-content" class="aboutus-entry-content">
<p>Maecenas facilisis</p>
<p>ullamcorper nunc</p>
</div>


Expected ouput:

<div id="about-content" class="aboutus-entry-content">
<p>
<div class="first-letter">M</div>
Maecenas facilisis</p>
<p>
<div class="first-letter">u</div>
ullamcorper nunc</p>
</div>

Answer

Try this:

$(document).ready(function() {
    $("p").each(function(index) {
        var textN = $(this).text();
        var firstWord = textN.charAt(0);
        console.log(index + ": " + firstWord);
        $(this).prepend('<div class="first-letter">' + firstWord + '</div>');
        /*$(this).append('<div class="first-letter">'+firstWord+'</div>');*/
    });
});

Demo JSFiddle