user3004305
user3004305

Reputation: 1

Span around last two letters of word with jquery?

I've spotted lots of examples of targeting specific works in a header or div using jQuery, but what I'm after is slightly different.

I'm using Jigoshop for an e-commerce site and would like to make the decimal places of the price of the products smaller than the rest of the numbers.

Currently, Jigoshop exports out the prices like so:

<div class="price">£300.00</div>

But ideally, I'd like this:

<div class="price">£300.<span class="decimals">00</span></div>

The full stop/decimal place can always be used as a separator if that helps.

Any help would be appreciated!

Thanks,

Adam.

Upvotes: 0

Views: 970

Answers (5)

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$(".price").html(function(i, html){
    return html.replace( /(\.\d+)$/, '<span class="decimals">$1</span>')
});

Demo: Fiddle

Upvotes: 5

gotofritz
gotofritz

Reputation: 3381

The simplest way would be

$( ".price" ).html( function( index, oldHtml ){
    return oldHtml.replace( /(\d\d)$/, "<span class='decimals'>$1</span>" );
});

EDIT: fixed so that it works for multiple prices. So it's the same as the top answer, with a slightly different RegExp (probably faster, but I doubt it would make much of a difference)

Upvotes: 2

Saturnix
Saturnix

Reputation: 10564

What you're trying to do is really bad practice. However, here's how you'd do that.

$('.price').each(function () {
    var p = $(this);
    var t = p.text().split('.');
    var s = $('<span></span>');
    s.attr('class', 'decimals');
    s.text(t[1])
    p.text("");
    p.text(t[0] + ".");
    p.append(s);
});

jsfiddle.

Upvotes: 0

fiddle Demo

$('div.price').html(function (_, old_html) {
    return old_html.substr(0, old_html.indexOf('.')) + '<span class="decimals">' + old_html.substr(old_html.indexOf('.')) + '</span>';
});


.html()

Upvotes: 1

Lars Ebert-Harlaar
Lars Ebert-Harlaar

Reputation: 3537

var price = $('.price').text();
price = price.split('.');
$('.price').html(price[0] + '.<span class="decimals">' + price[1] + '</span>');

But be aware that modifying the DOM via JS to archive some styling is a somewhat bad practice!

If you have multiple prices:

$('.price').each(function() {
    var price = $(this).text();
    price = price.split('.');
    $(this).html(price[0] + '.<span class="decimals">' + price[1] + '</span>');
}

Upvotes: 2

Related Questions