Targeting first letter of each word in h1 using javascript

I am trying to wrap the first letter of each word in my heading tags with a span class so that I can style them using CSS. I have tried to use a snippet I’ve found on here, but I have 2 h1 tags and it is taking the first one and repeating it for the second!

The function is this:

  $(document).ready(function() {
    var words = $('h1').text().split(' ');
    var html = '';
    $.each(words, function() {
      html += '<span class="firstLetter">' + this.substring(0, 1) + '</span>' + this.substring(1) + ' ';


So I have an h1 in the banner at the top, and another one at the start of the content, but the function is taking the top banner heading and replacing the content heading with it, but the span class is working!

I know you shouldn’t have 2 h1s, but I want to target all headings anyway, and its a CMS for a client so I can’t guarantee they won’t use multiple h1 going forwards, so I am testing it out!

>Solution :

As per OP’s request, this will "wrap the first letter of each word".

Since there are two <h1> elements (as OP said, very wrong), one should iterate them using each too, same way OP did with the words array.

$(document).ready(function() {

    $('h1').each( function(index, heading) {
      const words = $(heading).text().split(' ')
      let html = '';
      $.each(words, function() {
        html += '<span class="firstLetter">'+this.substring(0,1)+'</span>'+this.substring(1) + ' ';
span.firstLetter {
  color: violet;
<script src=""></script>

<h1>Lorem ipsum dolor sit amet</h1>


<h1>Bacon ipsum dolor amet biltong pork chop bacon</h1>

Leave a Reply