在GTM变量中用JavaScript/Regex查找子串及触发器配置求助
The core issue here is that your {{DLV - element}} variable isn’t actually a string (even though Tag Assistant displays it as a formatted string in debug mode)—it’s a DOM Element object. Your original code relies on the element’s auto-converted string representation (the one with line breaks you see in Tag Assistant), which is unreliable because line breaks can break string checks like includes() or regex word boundaries.
Instead of working with the string representation, we should directly inspect the DOM element and its parent hierarchy (since clicks might happen on child elements inside the collapsible container). Here’s a reliable solution:
Step 1: Create a Custom JavaScript Variable
In Google Tag Manager, create a new Custom JavaScript variable with this code:
function () { // Replace with your element variable if needed (e.g., {{DLV - element}}) const targetElement = {{Click Element}}; // Recursively check if the element or any ancestor has the "collapsible" class function checkForCollapsible(el) { while (el) { // Check if the current element has the class if (el.classList && el.classList.contains('collapsible')) { return true; } // Move up to the parent element el = el.parentElement; } // No matching element found return false; } return checkForCollapsible(targetElement); }
Note: If you need to use your {{DLV - element}} instead of the built-in {{Click Element}}, just replace {{Click Element}} in the code with your variable.
Step 2: Update Your Click Trigger
Edit your existing Click Element trigger (or create a new one):
- Set the trigger type to
Click - All Elements(or the specific click type you require). - Add a condition: Your new Custom JS Variable equals
true. - Optional: Add additional conditions (like
Click Textmatches a pattern) to narrow down the trigger if needed.
Why Your Original Approach Failed
- The string representation of the element in Tag Assistant includes line breaks, which can split the "collapsible" substring across lines—breaking
includes()checks and regex\bword boundaries. - Relying on the string representation of a DOM element is fragile, as browsers can format this string differently. Directly interacting with the DOM element’s properties (like
classList) is always more reliable.
内容的提问来源于stack exchange,提问作者Manuel-BWK

