I want to grab all of these elements with a GTM variable so that I could send all the product names to Google Analytics whenever a person enters this section of the site.
I've tried using the DOM element variable, a JS variable with document.getElementByClassName and document.querySelector and querySelectorAll, however all of these return the value of null. I am not that experienced with JS, what am I doing wrong?
Thanks in advance :^)
Edit:
I made a clone from your picture. You can see there are 3 items on the page.
I use grabNames` function to return an array of these 3 items' names.
So, you can copy grabNames function to your GTM custom javascript page.
function grabName() {
var elems = document.querySelectorAll('.name'); // return elements class = name
var prodctList = []; // make a new array
for (let i = 0; i < elems.length; i ++) // loop entire elems and push each elem name to the list
prodctList.push(elems[i].innerText);
return prodctList; // return array
}
var arr = grabName();
console.log(arr)
.details {
margin-bottom: 15px;
padding: 5px;
border: 1px solid black;
}
<div class="details">
<div class="summary">
<div class="summary__item">
<a class="name">
prodct name 1
</a>
</div>
</div>
</div>
<div class="details">
<div class="summary">
<div class="summary__item">
<a class="name">
prodct name 2
</a>
</div>
</div>
</div>
<div class="details">
<div class="summary">
<div class="summary__item">
<a class="name">
prodct name 3
</a>
</div>
</div>
</div>
I'm not sure how you wrote your code. any error message?
I think the code below should works
document.getElementByClassName('name');
// or
document.querySelectorAll('.name');
You can see these post: