David Vallejo - Web Analyst

#Tip - How to quickly debug/qa data attributes

Web Analytics

With the years I learned that using CSS selectors to track user actions is really great but sadly I learned too that it's really dangerous too.

It's true that we won't need to ask the IT team to add some dataLayer or ga pushes into the page, and therefore saving a lot of precious time, but in the other side, any single page update or testing will break our tracking.

Now I try to use data attributes whereas is possible, since those are more likely going to be kept for layout updates.

Checking elements for data attributes can be a tedious task, so I'm going to show you a little piece of code that I hope will make your life easier if you based some of your implementations on data attributes.

On this little snippet is where the magic happens:

(function() {
    
    var elements = [].slice.call(document.querySelectorAll('*')).filter(function(el) {
        if (typeof (el.dataset) != "undefined")
            return Object.keys(el.dataset).length != 0;
    });
    
    var data = [];
    var i = elements.length;
    
    while (i--) {
        var el = JSON.parse(JSON.stringify(elements[i].dataset));
        data.push(el);
        el["_element_type"] = elements[i].nodeName;
    }
    console.table(data);

})();

As an example I'm going to show you the output for Google Tag Manager's Homepage.

This has been a great time saver for me. Hope you find it useful too :)