ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

HTML Element Attribute Summation

HTML

Goal -- WPM

Ready
Exercise Algorithm Area
1function sumAttributeValues(doc, tagName, attributeName) {
2let totalSum = 0;
3const elements = doc.getElementsByTagName(tagName);
4
5if (!elements) {
6return 0;
7}
8
9// Loop through all found elements
10for (let i = 0; i < elements.length; i++) {
11const element = elements[i];
12const attributeValue = element.getAttribute(attributeName);
13
14if (attributeValue !== null) {
15// Attempt to convert attribute value to a number
16const numericValue = parseFloat(attributeValue);
17
18// Check if the conversion was successful and it's a valid number
19if (!isNaN(numericValue)) {
20totalSum += numericValue;
21}
22}
23}
24
25return totalSum;
26}
27
28function getDocumentFromHtmlString(htmlString) {
29if (!htmlString || typeof htmlString !== 'string') {
30console.error('Invalid HTML content provided.');
31return null;
32}
33const parser = new DOMParser();
34const doc = parser.parseFromString(htmlString, 'text/html');
35return doc;
36}
37
38function processHtmlForAttributeSum(htmlContent, targetTag, targetAttribute) {
39if (!targetTag || typeof targetTag !== 'string' || targetTag.length === 0) {
40console.error('Invalid target tag name provided.');
41return -1; // Indicate error
42}
43if (!targetAttribute || typeof targetAttribute !== 'string' || targetAttribute.length === 0) {
44console.error('Invalid target attribute name provided.');
45return -1; // Indicate error
46}
47
48const doc = getDocumentFromHtmlString(htmlContent);
49if (!doc) {
50return -1; // Error occurred during parsing
51}
52
53const sum = sumAttributeValues(doc, targetTag, targetAttribute);
54
55return sum;
56}
57
58// Example Usage:
59// const html = '<html><body><div data-value="10">A</div><div data-value="20.5">B</div><span data-value="abc">C</span><div data-value="30">D</div></body></html>';
60// const divSum = processHtmlForAttributeSum(html, 'div', 'data-value');
61// console.log('Div data-value sum:', divSum); // Expected: 60.5
62// const spanSum = processHtmlForAttributeSum(html, 'span', 'data-value');
63// console.log('Span data-value sum:', spanSum); // Expected: 0 (because 'abc' is not a valid number)
64// const nonExistentSum = processHtmlForAttributeSum(html, 'p', 'data-value');
65// console.log('P data-value sum:', nonExistentSum); // Expected: 0
Algorithm description viewbox

HTML Element Attribute Summation

Algorithm description:

This algorithm calculates the sum of numeric values of a specified attribute across all HTML elements matching a given tag name. It parses the HTML, finds all relevant elements, extracts the attribute value, converts it to a number, and adds it to a running total. This is useful for aggregating data points stored as attributes in HTML, such as prices, quantities, or scores.

Algorithm explanation:

The `processHtmlForAttributeSum` function validates the target tag and attribute names and then parses the HTML content into a `Document` object. The `sumAttributeValues` function iterates through all elements of the specified `tagName` using `doc.getElementsByTagName`. For each element, it retrieves the `attributeName` using `element.getAttribute`. If the attribute exists, it attempts to convert its value to a floating-point number using `parseFloat`. It then checks if the result is a valid number using `!isNaN()`. If it is, the numeric value is added to `totalSum`. The time complexity is O(N) due to DOM traversal, where N is the total number of nodes. Space complexity is O(M) for the `HTMLCollection`, where M is the number of matching tags. Edge cases handled include missing attributes, non-numeric attribute values, non-existent tags, and invalid input strings.

Pseudocode:

function sumAttributeValues(document, tagName, attributeName):
  total_sum = 0
  get all elements with tagName from document
  for each element found:
    attribute_value = get attribute_name from element
    if attribute_value is not null:
      numeric_value = convert attribute_value to number
      if numeric_value is a valid number:
        total_sum = total_sum + numeric_value
  return total_sum

function processHtmlForAttributeSum(htmlContent, targetTag, targetAttribute):
  validate targetTag and targetAttribute
  parse htmlContent into document
  if parsing failed:
    return error indicator
  return sumAttributeValues(document, targetTag, targetAttribute)