How to style the first word of a sentence

A cool trick is to sometimes style the first word in a sentence. This is particularly useful with headlines by underlining the first word.

first word headline underline image
Headline with the first word underlined

Insert a headline block, make it an H2 and assign it a class of underline-first-word from the options on the right.

H2 class assignment
H2 class assignment

Now the fun part. We are going to write some JavaScript code that will split any sentence we want into <span></span> elements to assist us with styling. No need to mess with the headline HTML code, either, the code will do the work for us! Create a GeneratePress hook element and set it to be displayed at the footer. On the element Display Rules, select where you want that element to appear. You can select “Entire Site”, but if you only want to style a headline on a certain page, select only that page so that the code doesn’t load on all the pages of your site. Enter the following code into the hook text area:

var h1s = document.getElementsByTagName('h2');
for(var i=0; i < h1s.length; i++) {
    var t = h1s[i];
    t.innerHTML = '<span>' + t.innerHTML . split(' ') . join('</span> <span>') +  '</span>'; 

Your element should like something like this.

Split sentence hook image
Custom GeneratePress hook

Make sure that there is a space between the two <span> elements in this part of the code:

join('</span> <span>')

Now, write some simple CSS to target the first word of your headline:

h2.underline-first-word span:first-child {
  text-decoration: underline;

And voila! Your H2 headline should look something like this:

first word headline underline image
Headline with the first word underlined

Of course, you can apply any kind of styling of your choosing to your headline as long as the underline-first-word class is present!