简体   繁体   中英

Getting all the elements containing numeric data from a webpage using jQuery?

I was wondering, is there any way that I can get all the elements ie div s span s etc containing the numeric data? What I want to do is get all of them and then format them using a currency formatter jquery plugin. The code that I'm using now is:

var options = {
    symbol: "",
    decimal: ".",
    thousand: ",",
    precision: 2,
    format: "%s%v"
};

$(".namount").each(function () {
    var formattedNum = accounting.formatMoney($(this).text(), options)
    $(this).html(formattedNum);
});

$(".totalsale").each(function(){
    var formattedNum = accounting.formatMoney($(this).text(), options)
    $(this).html(formattedNum);
});

$(".totalpurchase").each(function(){
    var formattedNum = accounting.formatMoney($(this).text(), options)
    $(this).html(formattedNum);
});    

There are 4 to 5 more similar calls to each loop for different elements. The problem is, doing this won't be efficient. Is there any other way that I can achieve this.

Thanks

Since you have a class selector this is one of the best ways. Only change I would do is to use a multiple selector and the use the .text() method to update the value in the element

$(".namount, .totalsale, .totalpurchase").text(function (idx, text) {
    return accounting.formatMoney(text, options)
});

Another possible change you can think of is to narrow down the search context using a parent container element

You can do this by using class selector as suggested or you can achieve this using regular expression too.

Refer this

jQuery selector regular expressions

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM