Search code examples
javascriptcss-selectorsgoogle-tag-manager

Google Tag Manager - Custom Variable To Grab Text Located Near A Click of Interest


I'm looking to return the innertext of "How are we doing?", when a user clicks on the toggle-icon class. This is a FAQ table where the user can click a plus or minus icon to expand / collapse the menu. My goal is when the user interacts with the icon, I can grab the related text to use within Google Tag Manager as a variable.

I know you can climb up or down the DOM tree using css selectors but am not quite at the point where I understand it fully enough to get it working.

<div id="elementor-tab-title-2871" class="elementor-tab-title" data-tab="1" role="tab" aria-controls="elementor-tab-content-2871">
    <span class="elementor-toggle-icon elementor-toggle-icon-right" aria-hidden="true">
        <span class="elementor-toggle-icon-closed"><i class="fas fa-plus"></i></span>
            <span class="elementor-toggle-icon-opened"><i class="elementor-toggle-icon-opened fas fa-minus"></i></span>
            </span>
        <a href="" class="elementor-toggle-title">How are we doing?</a>
</div>


Solution

  • You can first create a trigger from type "Click - Just Links". On setting "This trigger fires on" choose -> "Some Link Clicks". Then choose "Click Classes" -> "contains" -> and put "elementor-toggle" into the free text field.

    Then go to the variables section within the UI and create a new javascript variable with:

    function() {
     var toggleTitle = document.getElementsByClassName("elementor-toggle-title");
      
     return toggleTitle[0].text;
    }
    

    Then use the trigger and variable in your tags and you will get the needed innertext.