Search code examples
jquerycss-selectors

Changing color of the second letter of a link


I've been trying to figure out how to target the second character of a link and change its color to red.

And I'm trying to target the second letter.

Without the nth-child(2), my code successfully changes the color of the whole link to red.

What am I doing wrong?

$(document).ready(function() {
  $(".header-title-text").find("a:nth-child(2)").css({
    color: 'red'
  });
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='header-title-text'>
  <a>title</a>
</div>


Solution

  • You can not directly add color to a letter, you need to rap it in some HTML element like span and then you can add the color.

    Working snippet:

    $(document).ready(function() {
      var secLetter = $(".header-title-text").find("a").text().split('')[1];
      $(".header-title-text").find("a").html($(".header-title-text").find("a").html().replace(secLetter, "<span class='red'>" + secLetter + "</span>"));
    });
    .red {
      color: red;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="header-title-text">
      <a href="abc.com">title</a>
    </div>