Advertisement
prabapro

GTM Click Element to CSS Path & Get last 100 characters

Mar 14th, 2024 (edited)
755
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Originally created by Simo Ahava: https://www.simoahava.com/analytics/create-css-path-variable-for-click-element/
  2. // Modified to return last 100 characters
  3.  
  4. function() {
  5.   // Build a CSS path for the clicked element
  6.   var originalEl = {{Click Element}};
  7.   var el = originalEl;
  8.   if (el instanceof Node) {
  9.     // Build the list of elements along the path
  10.     var elList = [];
  11.     do {
  12.       if (el instanceof Element) {
  13.         var classString = el.classList ? [].slice.call(el.classList).join('.') : '';
  14.         var elementName = (el.tagName ? el.tagName.toLowerCase() : '') +
  15.             (classString ? '.' + classString : '') +
  16.             (el.id ? '#' + el.id : '');
  17.         if (elementName) elList.unshift(elementName);
  18.       }
  19.       el = el.parentNode
  20.     } while (el != null);
  21.     // Get the stringified element object name
  22.     var objString = originalEl.toString().match(/\[object (\w+)\]/);
  23.     var elementType = objString ? objString[1] : originalEl.toString();
  24.     var cssString = elList.join(' > ');
  25.     // Return the CSS path as a string, prefixed with the element object name
  26.     return (cssString ? elementType + ': ' + cssString : elementType).slice(-100);
  27.   }
  28. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement