Hammad Munir Hammad Munir - 3 months ago 13
Javascript Question

Get first letter of every paragraph from specific div javascript/jquery

I want to get the first letter of every paragraph from specific div using javascript or jquery and append that letter into the 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

Comments