Home > Mobile >  Targeting first letter of each word in h1 using javascript
Targeting first letter of each word in h1 using javascript

Time:05-19

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 >'   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!

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!

CodePudding user response:

If you want to style the first letter of every word in each heading, then you can wrap each word inside the headings within a <span> and then style the first letter of these spans using the ::first-letter CSS pseudo element.

const headingEls = document.querySelectorAll("h1");

headingEls.forEach((h) => {
  h.innerHTML = h.textContent
    .split(" ")
    .map((w) => `<span>${w}</span>`)
    .join(" ");
});
h1 span {
  display: inline-block;
}

h1 span::first-letter {
  font-size: 3rem;
  color: palevioletred;
}
<h1>Heading</h1>
<h1>Another Heading</h1>

If you just want to style the first letter of each heading, you don't need JS, you can do it by using only the ::first-letter CSS pseudo element.

h1::first-letter {
  font-size: 3rem;
  color: palevioletred;
}
<h1>Heading</h1>
<h1>Another Heading</h1>

CodePudding user response:

const h1 = document.getElementsByTagName("H1");
for (const item of h1) {
    item.innerHTML = "<span>"   item.innerHTML[0]   "</span>"   item.innerHTML.slice(1)
}

Assuming that the your h1 tags have no children. Its easy to modify this to get the correct result though.

CodePudding user response:

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 >' 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>

CodePudding user response:

This should work:

.firstLetter
{
color:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>Hello World</h1>
<h1>Goodbye World</h1>

<script>
        var h1s = document.getElementsByTagName('h1');
        for(const h1 of h1s)
        {
            let text = h1.innerText.split(' ');
            let html = "";
            for(const word of text)
            {
             html  = '<span >'   word.substring(0, 1)   '</span>'   word.substring(1)   ' ';
            }
            h1.innerHTML = html;
        }
        
</script>

CodePudding user response:

To style each first letter of every word in every heading, you can use jQuery's .html() (as you're using jQuery in your question). This will loop over each h1, and replace the text within it with the returned value. The new value replaces the first letter of each word (referred to using $& in the replacement argument) matched using the regular expression \b\w (which matches a word boundary (\b) followed by a character (\w)) with the character itself wrapped in <span> tags:

$("h1").html(function(i, txt) {
  return txt.replace(/\b\w/g, '<span >$&</span>');
});
.firstLetter {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1>This is a heading</h1>
<h1>This is another heading</h1>

  • Related