GTM Trick: Getting Text of Parent/sibling Element On Link Click
Disclaimer: Always use (if possible) DataLayer for sending user interaction information to Google Analytics via GTM.
Sometimes, we need to get the "text" of parent/sibling element of the clicked linked/element. For example,
- Set the title of the article as event label when user clicks on the "Read More" on the article listing page.
- Set the title of the article as event label when user clicks shares the article on social media.
- Get the "Promotion Text" as shown the screenshot above.
In this article, I will focus on solving this using Custom Code variable of GTM.
can use the “closest()” JavaScript method to find this information.
MDN Reference: Element.closest()
Step by Step solution:
1. Create a Custom Code Variable in GTM
2. Use the following code to get the Class or ID of the parent element
function() { 'use strict'; try { var clickEvent = {{Click Element}}; var clickSelector = clickEvent.closest('.card-body'); if (!clickSelector) return false; var clickText = clickSelector.querySelector('.Card-subtitle').innerText.trim(); return clickText; } catch (err) { console.log(err); }
}
3. Verify in “GTM Preview Mode”
Hopefully, this post will serve as a useful guide for click tracking using to Google Tag Manager.