Skip to content

getElementAttribute — GTM Variable Template for DOM

VARIABLES › DOM
getElementAttribute EXTENDED DOM

Gets an attribute value from a DOM element via the dataLayer.



Examples

Get href attribute
INPUT
Element Path: gtm.element
Attribute: href
OUTPUT
/products/shoes
Get tag name
INPUT
Element Path: gtm.element
Attribute: tagName
OUTPUT
A

GTM Configuration

This is what you'll see when you open this variable in Google Tag Manager. Hover the icons for details.

Read-only Preview
getElementAttribute
Element Path
💾 The dataLayer path to the element. Use "gtm.element" for clicked element, or add ".parentElement" to traverse up.

Supported formats:
  ✓ Clicked element: "gtm.element"
  ✓ Parent: "gtm.element.parentElement"
  ✓ Grandparent: "gtm.element.parentElement.parentElement"
Attribute
💾 The attribute to retrieve from the element.
Custom Attribute Name
💾 Name of the custom attribute to retrieve.

Supported formats:
  ✓ Data attribute: "data-product-id", "data-gtm-click"
  ✓ Any attribute: "aria-label", "title"
Input Setup
Input Function (optional)
⚙️ Optional pre-processing function applied to the element path before retrieval.
Result Handling
Output Function (optional)
⚙️ Optional function to apply to the attribute value before returning it (e.g., val => val.toLowerCase(), val => val.split(' ')[0] for first class). Useful for chaining transformations.

Related Variables

Same category: DOM


Under the Hood

📜 View Implementation Code
/**
 * Gets an attribute value from a dataLayer element path.
 * 
 * @param {string} data.src - The element path in dataLayer (e.g., "gtm.element" or "gtm.element.parentElement").
 * @param {string} data.attr - The attribute to retrieve (href, class, id, data-*, tagName, innerText, custom).
 * @param {string} [data.customAttr] - Custom attribute name when attr is "custom".
 * @param {Function|string} [data.out] - Optional output handler.
 *
 * Direct-mode specific parameters:
 * @param {Function} [data.pre] - Optional pre-processor function.
 * 
 * @returns {string|undefined} The attribute value, or undefined if not found.
 *
 * @framework ggLowCodeGTMKit
 */
const copyFromDataLayer = require('copyFromDataLayer');

const attributePathCache = {};
const getAttributePath = function(attr) {
    if (attributePathCache[attr]) return attributePathCache[attr];
    let path;
    if (attr.indexOf('data-') === 0) {
        const camelCase = attr.substring(5).split('-').map(function(text, index) {
            if (index === 0) return text;
            return text.charAt(0).toUpperCase() + text.substring(1);
        }).join('');
        path = '.dataset.' + camelCase;
    } else if (attr === 'tagName') {
        path = '.tagName';
    } else if (attr === 'innerText') {
        path = '.innerText';
    } else {
        path = '.attributes.' + attr + '.value';
    }
    attributePathCache[attr] = path;
    return path;
};

const getElementAttribute = function(elementPath, attribute, customAttribute) {
    if (!elementPath || !attribute) {
        return undefined;
    }
    
    const actualAttr = attribute === 'custom' ? customAttribute : attribute;
    
    if (!actualAttr) {
        return undefined;
    }
    
    const fullPath = elementPath + getAttributePath(actualAttr);
    let value = copyFromDataLayer(fullPath);
    
    if (actualAttr === 'innerText' && typeof value === 'string') {
        value = value.trim().split('\n').join(' ').split('\t').join(' ');
    }
    
    return value;
};
const safeFunction = fn => typeof fn === 'function' ? fn : x => x;
const out = safeFunction(data.out);
// ===============================================================================
// getElementAttribute - Direct mode
// ===============================================================================
const applyCast = (castFn, value) => safeFunction(castFn)(value);
const elementPath = applyCast(data.pre, data.src);
return out(getElementAttribute(elementPath, data.attr, data.customAttr));
// ===============================================================================
// getElementAttribute(...) – Apply Mode
// ===============================================================================
/*
return function(elementPath, attribute) {
   attribute = data.rp1 ? data.attr : attribute;
   const customAttribute = data.rp1 ? data.customAttr : undefined;
   return out(getElementAttribute(elementPath, attribute, customAttribute));
};
*/


___WEB_PERMISSIONS___

[
  {
    "
🧪 View Test Scenarios (6 tests)
✅ '[example] Get href attribute'
✅ '[example] Get tag name'
✅ Test get data-* attribute converts to camelCase
✅ Test get innerText attribute cleans whitespace
✅ Test get attribute from parent element
✅ Test undefined element path returns undefined