Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

<script>
  $(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) + ' ';
      $('h1').html(html);
    });

  });
</script>

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!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) + ' ';
      })
      
      $(heading).html(html);
    })
    
});
span.firstLetter {
  color: violet;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

<hr>

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

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading