Search code examples
javascripthtmljqueryfont-face

jQuery replacing "small-caps" - Content is Duplicating HTML between <h3> tags


I found this HOT bit of jQuery that actually allows you to replicate "font-variant: small caps". Normally not an issue, but I'm using @font-face and little did I know that it doesn't play nicely with font-variant-small-caps in Chrome, Safari, IE. Long story short, the code is working SWEET but it has one drawback - for some reason it is searching for the first text string that is bracketed by and then that text string is repeated in later

example... code says:

<h3 class="small caps">I'm the FIRST heading</h3>
<h3 class="small caps">I'm SECOND</h3>

is altered by the script to produce this:

<h3 class="small caps">I'm the FIRST heading</h3>
<h3 class="small caps">I'm the FIRST heading</h3>

Here's the code that's doing the magic in jQuery:

    jQuery(document).ready(function($) {
        var text = $('h3.small-caps').html();
        $('h3.small-caps').html(text.replace(/\b([A-Za-z0-9])/g,'<span class="caps">$1</span>'));
        $('.caps').css('font-size',50);
    }); 

Solution

  • Try:

    jQuery(document).ready(function($) {
        $('h3.small-caps').each(function() {
            var $this = $(this);
            var text = $this.html();
            $this.html(text.replace(/\b([A-Za-z0-9])/g,'<span class="caps">$1</span>'));
        });
        $('.caps').css('font-size',50);
    });