Creating a JavaScript function that calculates the sum of values in a table

Here is a snippet of my HTML code:

<TR Row="1" CLASS="ThemeAlignCenter">
                <TD id="wrdActive_Row1" style="width: 50px"
                    CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD>

... more rows

I am looking to include a JavaScript at the bottom of the page to sum up all the values of lblactive_row1 whenever it appears on the page (in this example, the number 6).

Edit: more source

    <TABLE style="" border="0" CLASS="rdThemeDataTable" id="dtWardData"
                cellspacing="0">
                <COL id="wrdActive"></COL><COL id="wrdOccupied"></COL>
                <TR Row="1" CLASS="ThemeAlignCenter">
                    <TD id="wrdActive_Row1" style="width: 50px"
                        CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">4</SPAN></TD>
                    <TD id="wrdOccupied_Row1" style="width: 50px"
                        CLASS="rdThemeDataTableCell"><SPAN id="lblOccupied_Row1">4</SPAN></TD>
                </TR>
            </TABLE>

   <TABLE style="" border="0" CLASS="rdThemeDataTable" id="dtWardData"
                cellspacing="0">
                <COL id="wrdActive"></COL><COL id="wrdOccupied"></COL>
                    <TD id="wrdActive_Row1" style="width: 50px"
                        CLASS="rdThemeDataTableCell"><SPAN id="lblactive_Row1">6</SPAN></TD>
                    <TD id="wrdOccupied_Row1" style="width: 50px"
                        CLASS="rdThemeDataTableCell"><SPAN id="lblOccupied_Row1">2</SPAN></TD>
                </TR>
            </TABLE>

    Repeat...

This pattern continues for around 10 tables within the same source. I cannot modify the generated HTML as it comes from a third-party tool. My only option is to add a small script at the end of the page.

Answer №1

When it comes to selecting elements from your HTML, the approach may vary depending on whether you are using jQuery or not.

If you are utilizing jQuery, the following code snippet could be helpful:

var total = 0;
$('table tr.ThemeAlignCenter > td.rdThemeDataTableCell > span').each(function(i) {
    total += parseInt($(this).text());
});

For those working without jQuery and assuming that your <table> element has an id of data, consider a solution like this:

var tbl = document.getElementById('data');
var cells = tbl.getElementsByTagName('td');

var total = 0;
for (var i = 0, limit = cells.length; i < limit; i++) {
    var td = cells[i];
    if (td.className === 'rdThemeDataTableCell') {
        var elem = td.getElementsByTagName('span')[0];
        total += parseInt(elem.innerHTML);
    }
}

UPDATE: The code has been refactored to handle multiple tables (in case changing the table IDs is not an option):

function sumTable(tbl) {
    var cells = tbl.getElementsByTagName('td');

    var total = 0;
    for (var i = 0, limit = cells.length; i < limit; i++) {
        var td = cells[i];
        if (td.className === 'rdThemeDataTableCell') {
            var elem = td.getElementsByTagName('span')[0];
            total += parseInt(elem.innerHTML);
        }
    }

    return total;
}

var tables = document.getElementsByTagName('table');
var results = [];
for (var i = 0, limit = tables.length; i < limit; i++) {
    var total = sumTable(tables[i]);
    results.push(total);
}

Answer №2

If you need a solution, consider implementing the following:

function countRows() {
    var count = 0;
    var divs = document.getElementsByTagName('div');

    for(var j=0; j<divs.length; j++) {
        if(divs[j].getAttribute('class') === 'row') {
            count += parseInt( divs[j].innerHTML, 10);
        }
    }

    return count;
}

connect countRows() to an eventListener

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with modal not being able to close the embedded video iframe

I have created a demo of a video in my footer that uses external CSS files and works perfectly. However, when I added it to the project, everything works except for closing the video. After clicking the play button in the footer, a modal appears on the sc ...

Alternative method for handling web requests in case JavaScript is not enabled

Issue: i) I am developing a JSF2 application and need to implement a tab control on a page. When a user clicks on a tab, the content for the panel below should be loaded from an xhtml file on the server using an ajax call. ii) I want this functionality ...

how to execute Vue-Js method just one time

Is there a way to add a random number (ranging from 0 to the price of an item) to one of the data properties in Vue.js, but only once when the page is initially loaded? I am unable to use mounted and computed because I need to pass a parameter to the funct ...

Steps for interacting with a button of the <input> tag in Selenium using Python

As I attempt to complete a form submission, I encounter an issue where clicking the submit button does not produce any action. It seems that the problem lies with the button being tagged as <input>: <input type="submit" name="submit ...

Check if a specific string is present in an array using JavaScript

When working with SQL, we can easily check if a string is in a list using the following syntax: Column IN ('a', 'b', 'c') But how can we achieve this in JavaScript without it being so cumbersome? if (expression1 || expressi ...

Unable to collapse the Bootstrap dropdown menu

For the life of me, I can't seem to find a solution to my problem. I'm currently working on creating a responsive navbar for my website by following a tutorial. The goal is to make it mobile-friendly with a button that expands the menu on smaller ...

Fetch information from the input field and send it to the Redux state

Looking for a solution - I'm working on a simple todo app where I need to store user input value in the redux state. The input value is currently stored in local state until the user clicks the "add" button. The main issue : How can I pass this input ...

Using jQuery to reference my custom attribute---"How to Use jQuery to reference My

Can you explain how to reference a tag using a custom attribute in jQuery? For example, if I have a tag like this: <a user="kasun" href="#" id="id1">Show More...</a> I want to reference the tag without using the id. So instead of using: $( ...

Navigating through the world of WebSQL data entry

I've encountered a challenge while utilizing WebSQL for my Chrome Extension. This is my first experience with it, so I decided to refer to this tutorial and modify it to suit my requirements: http://www.html5rocks.com/en/tutorials/webdatabase/todo/ B ...

Learning how to utilize localStorage in conjunction with a color picker to modify the --var of :root

After spending an entire afternoon on my JavaScript issue as a beginner, I have a specific goal in mind: allowing the user to select and change the main color of the page. To implement this, I inserted a color picker in my HTML: <input type="color ...

Does the entire state get replaced every time a change is made if the state is immutable?

Is it necessary to replace the entire state if it is immutable? Otherwise, wouldn't mutating the state occur? Are top-level keys maintained as distinct immutable objects? Wouldn't changing anything necessitate replacing the entire state by defin ...

Form confirmation popup with JQuery displaying input values upon submission click

Could anyone assist me with creating a form that displays a popup after submission, showing the entered values for confirmation along with edit and submit buttons? I have found several examples online, but none are exactly what I need. Your help would be ...

Troubleshooting: Angular 2 View not reflecting changes after array push

I have encountered an issue with my two child components. They are both meant to share data from a json file that I load using the http.get/subscribe method. Oddly enough, when I try to push new data into the array, it doesn't seem to update in the vi ...

Adjust the height of an element using CSS based on the height of another

Is there a way to have two divs per row, where the second div always displays its full content and the height of the first div matches the height of the second div? If the content in the first div exceeds the height, it should be scrollable. I've atte ...

Item 'unreachable' displayed in Firefox console

I am working with several divs that have the class='class_name'. I have also defined var A = document.getElementsByClassName('class_name'); console.log(A[0]); Upon checking in the Chrome console, it displays: <div class="class_n ...

What is the process of transforming a string into a JSON object?

var str = '""{""as"":""N9K-93180YC-EX""}""'; I attempted to remove the extra quotes using a regular expression: var str1 = str.replace(/\"/g, ""); After removing the extra quotes, the string now looks like "{as:N9K-93180YC-EX}". However, ...

Issues arise when attempting to utilize Async/Await with a gRPC method

Here is the code snippet used to initialize a gRPC server: export const initServer = async (finalPort: number): Promise<string> => { let initStatus = 'initial'; gRPCserver.addService(webcomponentHandler.service, webcomponentHandler.h ...

Use JavaScript to limit Google Analytics and Yandex.Metrica to track only the referral sources and screen sizes

I prefer not to include external JavaScript on my website for unnecessary tracking purposes. However, I do need to gather referrer and screen size information, which cannot be achieved with a regular HTML img tag alone. What is the most standard-complian ...

I am facing an issue with my react-app where it compiles successfully without any errors, but it is not rendering any elements

JavaScript file to run with npm start: import React from 'react'; import ReactDOM from 'react-dom'; import { BrowserRouter as Router } from 'react-router-dom'; import Routes from './routes'; ReactDOM.render( <R ...

What is the best way to add a div container to a particular section of a webpage?

I have come across many solutions that involve using JQuery, but I am specifically looking for a pure JS method. Currently, I create a div, add content to it using Create Element and innerHTML, and then use appendChild to place it at the bottom of the body ...