Apply css to last character in WordPress menu items

I am trying to apply some css to the current viewed menu item on a WordPress site. I can apply css to the whole item, but want to apply something to specifically just the last character.

Does anyone have any thoughts on how to go about this?

Read More

Thanks.

Related posts

Leave a Reply

2 comments

  1. The is no cross browser solution to achieve it using pure CSS.

    You can either using PHP or javascript to get the last character and style it or you can wrap that last character in another element like <span> and style it using css as normally.


    EDIT: Here is the javascript approach:

    <p class="test">This is a test</p>
    
    var targets = document.getElementsByClassName('test');
    for(i=0; i<targets.length; i++) {
        var html = targets[i].innerHTML;
        targets[i].innerHTML = html.substr(0, html.length-1)
            + "<span class='lastChar'>"
            + targets[i].innerHTML.substr(-1)
            + "</span>";
    }
    

    Fiddle Demo

  2. As Felix said, there is no cross browser solution to achieve it using pure CSS. I would reccommend writing simple js code to split menu item and add span with class to last letter.

    $('document').ready(function() {
      var item = $('.current-menu-item').children().html();
      $('.current-menu-item').children().html(item.substr(0, item.length - 1) + '<span class="last">' + item.substr(-1) + '</span>');
    });