Tried a lot of solutions (like these https://dev.to/dailydevtips1/javascript-loop-queryselectorall-results-j6) but can’t get the loop to work in GTM/Google Tag Manager.
My working script – not very good of course
var helloUrl = document.querySelectorAll('a[id*="hellotracklink"]')[0];
helloUrl.href = helloUrl.href + '?utm_source=' + utm_source + '&utm_medium=' + utm_medium + '&utm_campaign=' + utm_campaign + '&utm_term=' + utm_term + '&utm_content=' + utm_content + '&lpurl=' + lpUrl;
var helloUrl = document.querySelectorAll('a[id*="hellotracklink"]')[1];
helloUrl.href = helloUrl.href + '?utm_source=' + utm_source + '&utm_medium=' + utm_medium + '&utm_campaign=' + utm_campaign + '&utm_term=' + utm_term + '&utm_content=' + utm_content + '&lpurl=' + lpUrl;
var helloUrl = document.querySelectorAll('a[id*="hellotracklink"]')[2];
helloUrl.href = helloUrl.href + '?utm_source=' + utm_source + '&utm_medium=' + utm_medium + '&utm_campaign=' + utm_campaign + '&utm_term=' + utm_term + '&utm_content=' + utm_content + '&lpurl=' + lpUrl;
var helloUrl = document.querySelectorAll('a[id*="hellotracklink"]')[3];
helloUrl.href = helloUrl.href + '?utm_source=' + utm_source + '&utm_medium=' + utm_medium + '&utm_campaign=' + utm_campaign + '&utm_term=' + utm_term + '&utm_content=' + utm_content + '&lpurl=' + lpUrl;
- My failing script in GTM*
var helloUrl = document.querySelectorAll('.hellotracklink');
for (var i = 0; i < helloUrl.length; i++) {
helloUrl.href = helloUrl.href + '?utm_source=' + utm_source + '&utm_medium=' + utm_medium + '&utm_campaign=' + utm_campaign + '&utm_term=' + utm_term + '&utm_content=' + utm_content + '&lpurl=' + lpUrl;
}
3
Answers
Since all the tags you have start with "hellotracklink", you can simply use a single querySelectorAll to grab them all, and then iterate over them using a forEach or for loop.
basic sample like u case : https://jsfiddle.net/u6xaqyc8/
so you can find them like
You’re almost there with your failing script in GTM, but you’re missing the indexing for every single element in the NodeList that querySelectorAll returned. Utilizing helloUrl[i], you must access each element inside the loop. Here’s the updated script:
This will loop through all the elements with the class .hellotracklink, and for each one, it will append the query parameters to the href attribute as intended.
try it bro
By implementing these corrections, your script should correctly loop through all elements with the class hellotracklink and update their href attributes with the appropriate UTM parameters.