Display Count

Counts the number of data-count-item elements inside a named data-count-group and writes the total into any matching data-count-display element. Supports multiple independent counters on the same page via unique name identifiers.

countjavascriptdata-attributescmsdynamic
Display Count preview

Code

index.html
html
<p>We have <span data-count-display="jobs">0</span> open positions</p>

<div class="grid" data-count-group="jobs">
  <div class="grid-item" data-count-item></div>
  <div class="grid-item" data-count-item></div>
  <div class="grid-item" data-count-item></div>
  <div class="grid-item" data-count-item></div>
  <div class="grid-item" data-count-item></div>
</div>
script.js
javascript
function initDisplayCount() {
  document.querySelectorAll('[data-count-group]').forEach(group => {
    const name  = group.dataset.countGroup;
    const count = group.querySelectorAll('[data-count-item]').length;
    document.querySelectorAll(`[data-count-display="${name}"]`).forEach(display => display.textContent = count);
  });
}

// Initialize Display Count
document.addEventListener('DOMContentLoaded', () => {
  initDisplayCount();
});

Guide

data-count-group

Add to a parent element that wraps the items you want to count. Set its value to a unique name (e.g. data-count-group="jobs").

data-count-item

Add to each element inside the group that should be counted. No value needed — the script counts all matching descendants.

data-count-display

Add anywhere on the page with a value matching the group name (e.g. data-count-display="jobs"). Its text content will be replaced with the item count on DOMContentLoaded.

Multiple Counters

Use unique names for each counter. For example: data-count-group="jobs", data-count-group="articles", and data-count-group="services" each pair with their own data-count-display.