JQuery.each () will not iterate independently

I am using the following jQuery chunk to apply span styles to currency symbol and decimals of a bunch of monetary values.

$('td.priceBox').each(function() {
    $(this).html('<span class="price_currency price_element">' + $(this).html().substr(0, 1) // this styles the currency unit
    + "</span>" + $(this).html().substr(1, $(this).html().length-3) // this leaves the rounded value as is
    + '<span class="price_cents price_element">'
    + $(this).html().substr(-2)
    + "</span>") // this styles the decimals
});

      

This code works for the first value on the page eg. "$ 180.65", but then copies that value and replaces each value on the "$ 180.65" page.

What am I doing wrong? How can I get this to iterate independently for each td.priceBox

?

Note. The content is td.priceBox

dynamically generated and I don't have access to them. I cannot write lines per line.

EDIT: I had another script designed to remove the decimal $('.bannerContent td').html($('.bannerContent td').html().replace(".",""));

. This was targeting the same td, but did not identify it by class. This successfully removed the decimal, but for some reason it broke the .each () method. Why?

+3


source to share


2 answers


$('.bannerContent td').html($('.bannerContent td').html().replace(".",""));

      

This code replaces everything td

with the HTML of the first one. This is because while the .html()

setter function applies to the entire jQuery suite, it only works on the first as a receiver. If you put it inside yours .each()

and use it $(this)

, it should work:



$('td.priceBox').each(function() {
    $(this).html($(this).html().replace(".",""));
    $(this).html('<span class="price_currency price_element">' + $(this).html().substr(0, 1) // this styles the currency unit
    + "</span>" + $(this).html().substr(1, $(this).html().length-3) // this leaves the rounded value as is
    + '<span class="price_cents price_element">'
    + $(this).html().substr(-2)
    + "</span>") // this styles the decimals
});

      

For details on how this works, see the jQuery documentation .html()

.

+4


source


I think this should work too:

$('td.priceBox').each(function() {
var content       = $(this).html(),
    span          = $('<span />'),
    span_currency = span.addClass('price_currency price_element').html(content.substr(0, 1)),
    span_cents    = span.addClass('price_cents price_element').html(content.substr(-2));

    // Remove current content
    $(this).empty();

    // Add currency
    $(this).append(span_currency);

    // Add rounded value
    $(this).append(content.substr(1, (content.length - 3)));

    // Add cents
    $(this).append(span_cents);

      



});

+3


source







All Articles