Search code examples
javascriptgoogle-tag-manager

Custom GTM Javascript variable to count number of <h[x]> elements


I'm trying to set up a custom Javascript variable for a client in Google Tag Manager. They want to know how many times an element – in this case, header tags – appear on a given page.

Does anyone have a solution for a CJS variable that counts:

  1. Number of total occurrences of a list of elements on a page. e.g. Total count of <h2> + <h3> + <h4>

  2. Total individual occurrences for each element. e.g. <h2> count; <h3> count; <h4> count

Ideally this would have a variable output, which could then be used as a parameter on a GA4 event tag, the displays the total combined element count, then the count for each individual element (which would obviously mean setting up multiple variables).

I have done a lot of searching on this and other sites, and experimented with what I found, but in the end I haven't been successful.

Context: I have some 101 coding knowledge, but am not a programmer.

Thanks in advance for any help.


Solution

  • Something like this should be what you're looking for:

    function(){
        return "Total Headings: " + document.querySelectorAll("h1, h2, h3, h4, h5, h6").length + 
            "; H1: " + document.querySelectorAll("h1").length +
            "; H2: " + document.querySelectorAll("h2").length +
            "; H3: " + document.querySelectorAll("h3").length +
            "; H4: " + document.querySelectorAll("h4").length +
            "; H5: " + document.querySelectorAll("h5").length +
            "; H6: " + document.querySelectorAll("h6").length;
    }
    This is what it returns on this SO page: 'Total Headings: 16; H1: 2; H2: 4; H3: 3; H4: 2; H5: 5; H6: 0'

    Feel free to change whatever you need in it.